﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAPbouiCOM;
using SAPbobsCOM;
using System.Xml;
using BoAddonBiz_FreightForwarder.UpLoad;
using System.Text.RegularExpressions;
using System.Collections;

namespace BoAddonBiz_FreightForwarder.BusinessBase
{
    abstract class B1Form_BusinessOperation_Base : SAPBoAddon.B1Form
    {
        #region global abstract variable
        protected abstract string AVA_OBNO { get; }
        protected abstract string AVA_BNO1 { get; }
        protected abstract string AVA_BNO2 { get; }
        protected abstract string AVA_BNO3 { get; }
        protected abstract string AVA_BNO4 { get; }
        protected abstract string AVA_BNO5 { get; }
        protected abstract string AVA_ODLG { get; }
        protected abstract string AVA_DLG1 { get; }
        protected abstract string AVA_DLG2 { get; }
        protected abstract string AVA_DLG3 { get; }
        protected abstract string AVA_DLG6 { get; }
        protected abstract string AVA_AirOrder { get; }
        protected abstract string AVA_AirOrderUsed { get; }
        protected abstract string AVA_OAOD { get; }
        protected abstract string AVA_OAOU { get; }
        protected abstract string SourceObject { get; }
        protected abstract string[] SumMapping { get; }
        protected abstract string BusinessType { get; }
        #endregion
        #region 预告单
        protected virtual string AVA_OPRE { get { return AVA_OBNO.Substring(0, 8) + "OPRE"; } }
        protected virtual string AVA_PRE1 { get { return AVA_BNO1.Substring(0, 8) + "PRE1"; } }
        protected virtual string AVA_PRE2 { get { return AVA_BNO2.Substring(0, 8) + "PRE2"; } }
        protected virtual string AVA_PRE3 { get { return AVA_BNO3.Substring(0, 8) + "PRE3"; } }
        protected virtual string AVA_PRE4 { get { return AVA_BNO4.Substring(0, 8) + "PRE4"; } }
        protected virtual string AVA_PRE5 { get { return AVA_BNO5.Substring(0, 8) + "PRE5"; } }
        #endregion

        #region globlal variable
        protected abstract string[] CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC { get; }

        protected int CargoCurrentOffset = 0;//货物信息的当前行
        protected int PortCurrentOffset = 0;//中转港信息的当前行
        static int _FileCurrentOffset = 0;//附件信息的当前行

        public static int FileCurrentOffset
        {
            get { return _FileCurrentOffset; }
            set { _FileCurrentOffset = value; }
        }

        readonly string[] CargoInfoSumItem = new string[] { "cargo_6", "cargo_8", "cargo_10", "cargo_12", "cargo_40", "cargo_24" };

        #region 主单、分单费用合计字段
        string[] MBLItemData = { "199", "197", "195", "1000062", "203", "270", "269", "268", "273", "271" };
        string[] SBLItemData = { "1000105", "1000104", "1000103", "1000122", "1000109", "276", "275", "274", "279", "277" };
        string[] MBLCharge = { "191", "193", "1000064" };
        string[] SBLCharge = { "1000099", "1000101", "1000124" };
        #endregion

        private Dictionary<string, string> _Cargo_UID_Field;
        /// <summary>
        /// uid-alias
        /// </summary>
        public Dictionary<string, string> Cargo_UID_Field
        {
            get
            {
                if (_Cargo_UID_Field == null)
                {
                    _Cargo_UID_Field = new Dictionary<string, string>();
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(this.CurrentForm.GetAsXML());
                    XmlNodeList nodes = xml.ChildNodes[1].SelectNodes(String.Format("//item/specific/databind[@table='{0}']", AVA_BNO1));
                    foreach (XmlNode node in nodes)
                    {
                        string uid = node.ParentNode.ParentNode.Attributes["uid"].Value;
                        string alias = node.Attributes["alias"].Value;
                        _Cargo_UID_Field.Add(uid, alias);
                    }
                }
                return _Cargo_UID_Field;
            }
        }

        private Dictionary<string, string> _Cargo_ComboBoxUID_Field;
        /// <summary>
        /// 货物信息中ComboBox控件
        /// </summary>
        internal Dictionary<string, string> Cargo_ComboBoxUID_Field
        {
            get
            {
                if (_Cargo_ComboBoxUID_Field == null)
                {
                    _Cargo_ComboBoxUID_Field = new Dictionary<string, string>();
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(this.CurrentForm.GetAsXML());
                    XmlNodeList nodes = xml.ChildNodes[1].SelectNodes(String.Format("//item[@type='113']/specific/databind[@table='{0}']", AVA_BNO1));
                    foreach (XmlNode node in nodes)
                    {
                        string uid = node.ParentNode.ParentNode.Attributes["uid"].Value;
                        string alias = node.Attributes["alias"].Value;
                        _Cargo_ComboBoxUID_Field.Add(uid, alias);
                    }
                }
                return _Cargo_ComboBoxUID_Field;
            }
        }


        private Dictionary<string, string> _BnsOperation_ComboBoxUID_Field;
        /// <summary>
        /// 主表ComboBox控件
        /// </summary>
        internal Dictionary<string, string> BnsOperation_ComboBoxUID_Field
        {
            get
            {
                if (_BnsOperation_ComboBoxUID_Field == null)
                {
                    _BnsOperation_ComboBoxUID_Field = new Dictionary<string, string>();
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(this.CurrentForm.GetAsXML());
                    XmlNodeList nodes = xml.ChildNodes[1].SelectNodes(String.Format("//item[@type='113']/specific/databind[@table='{0}']", AVA_OBNO));
                    foreach (XmlNode node in nodes)
                    {
                        string uid = node.ParentNode.ParentNode.Attributes["uid"].Value;
                        string alias = node.Attributes["alias"].Value;
                        _BnsOperation_ComboBoxUID_Field.Add(uid, alias);
                    }
                }
                return _BnsOperation_ComboBoxUID_Field;
            }
        }
        #endregion

        #region constructor
        public B1Form_BusinessOperation_Base()
        {
            this.frm_ItemEvent += new SAPBoAddon.IB1FormEvents.B1ItemEventEventHandler(B1Form_BusinessOperation_Base_frm_ItemEvent);
            this.frm_FormDataEvent += new SAPBoAddon.IB1FormEvents.B1FormDataEventEventHandler(B1Form_BusinessOperation_Base_frm_FormDataEvent);
            this.frm_ChooseFormListEvent += new SAPBoAddon.IB1FormEvents.B1ChooseFormListEventEventHandler(B1Form_BusinessOperation_Base_frm_ChooseFormListEvent);
            this.frm_MenuEvent += new SAPBoAddon.IB1FormEvents.B1MenuEventEventHandler(B1Form_BusinessOperation_Base_frm_MenuEvent);
        }
        #endregion

        #region events
        void B1Form_BusinessOperation_Base_frm_MenuEvent(SAPBoAddon.B1AddonBase.B1MenuEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {

            }
            else
            {
                if (pVal.MenuUID == "1287")//复制
                {
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_BaseEntry", 0, "");
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_PayApproved", 0, "N");
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_ReceApproved", 0, "N");
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_IsPickup", 0, "N");//提货
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_IsCustoms", 0, "N");//出口报关
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_IsClearance", 0, "N");//进口报关
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_IsDelivery", 0, "N");//送货
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_IsInsure", 0, "N");//投保
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_IsArrivePort", 0, "N");//到港
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_IsWarehouse", 0, "N");//仓储
                    //附件不复制
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO5).Clear();
                }
            }
        }

        void B1Form_BusinessOperation_Base_frm_ChooseFormListEvent(SAPBoAddon.B1AddonBase.B1ChooseFormList pVal, ref bool BubbleEvent)
        {
            if (pVal.Before_Action)
            {
                #region 过滤条件
                SAPbouiCOM.ChooseFromList cfl = this.CurrentForm.ChooseFromLists.Item(pVal.ChooseFromListUID);
                SAPbouiCOM.Conditions cons;
                SAPbouiCOM.Condition con;
                switch (pVal.ChooseFromListUID)
                {
                    case "CFL_OCRD"://委托单位
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup13";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "C";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_MN"://主单通知人
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup8";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_MR"://主单收货人
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup12";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_MS"://主单发货人
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup11";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_SN"://分单通知人
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup8";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_SR"://分单收货人
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup12";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_SS"://分单发货人
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup11";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_S2"://分单发货人
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup11";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_R2"://分单收货人
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup12";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_N2"://分单通知人
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "QryGroup8";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    case "CFL_OCRD_TD"://中转港-中转港代理
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "CardType";
                        con.CondVal = "S";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_AND;
                        con = cons.Add();
                        con.Alias = "validFor";
                        con.CondVal = "Y";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    /*主单*/
                    case "CFL_MBL":
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "U_Status";
                        con.CondVal = "P";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        con.Relationship = BoConditionRelationship.cr_OR;
                        con = cons.Add();
                        con.Alias = "U_Status";
                        con.CondVal = "R";
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                    //指定客服（员工）
                    case "CFL_Employee":
                        //根据组别选择相应客服(条件筛选)
                        Utils.SelectClientName(cfl);
                        //Utils.SelectClientName(cfl, this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO));
                        break;
                    case "CFL_ExpressCmp"://快递公司
                        break;
                    case "CFL_OCPR"://客户联系人
                        SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                        string str_CardCode = dbds.GetValue("U_CardCode", dbds.Offset).Trim();
                        cons = new SAPbouiCOM.Conditions();
                        con = cons.Add();
                        con.Alias = "CardCode";
                        con.CondVal = str_CardCode;
                        con.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        cfl.SetConditions(cons);
                        break;
                }
                #endregion
            }
            else
            {
                #region 执行结果
                if (pVal.Action_Success)
                {
                    SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                    if (pVal.ChooseFromListUID == "CFL_OCRD")//客户
                    {
                        dbds.SetValue("U_CardCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_CardName", dbds.Offset, pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        dbds.SetValue("U_CardEnglishName", dbds.Offset, pVal.SelectedObjects.GetValue("CardFName", 0).ToString());
                        dynamic Cntct = Utils.GetDefaultContractPerson(this.SBOCompany, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        if (Cntct != null)
                        {
                            dbds.SetValue("U_CntctCode", dbds.Offset, Cntct.FullName);
                        }
                        Utils.GetSalesPerson(dbds, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_SD")//起运港代理
                    {
                        dbds.SetValue("U_StartDelegateCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_StartDelegateName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        SAPbouiCOM.DBDataSource dbds3 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3);
                        dbds3.SetValue("U_SenderCode", dbds.Offset, dbds.GetValue("U_StartDelegateCode", dbds.Offset));
                        dbds3.SetValue("U_Sender", dbds.Offset, pVal.SelectedObjects.GetValue("CardFName", 0).ToString());
                        dbds3.SetValue("U_SendDetail", dbds.Offset, pVal.SelectedObjects.GetValue("U_DeliveryContent", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_ED")//目的港代理
                    {
                        dbds.SetValue("U_EndDelegateCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_EndDelegateName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        SAPbouiCOM.DBDataSource dbds3 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3);
                        dbds3.SetValue("U_ReceiverCode", dbds.Offset, dbds.GetValue("U_EndDelegateCode", dbds.Offset));
                        dbds3.SetValue("U_Receiver", dbds.Offset, pVal.SelectedObjects.GetValue("CardFName", 0).ToString());
                        dbds3.SetValue("U_ReceiverDetail", dbds.Offset, pVal.SelectedObjects.GetValue("U_DeliveryContent", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_TP")//中转港代理——add by Webb.Wen at 2012-03-08 15:25:59
                    {
                        dbds.SetValue("U_TPAgencyCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_TPAgencyName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_D")//指定代理名称
                    {
                        dbds.SetValue("U_DelegateCardCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_DelegateCardName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        if (pVal.FormTypeEx == B1FormTypes.ado_AVA_SE_BusinessOperation)
                        {
                            SAPbouiCOM.DBDataSource dbds3 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3);
                            if (dbds3.GetValue("U_Notifier", 0).Trim().Length == 0)
                            {
                                dbds3.SetValue("U_NotifierCode", dbds.Offset, dbds.GetValue("U_DelegateCardCode", 0).ToString());
                                dbds3.SetValue("U_Notifier", dbds.Offset, dbds.GetValue("U_DelegateCardName", 0).ToString());
                                dbds3.SetValue("U_NotificationDatail", dbds.Offset, pVal.SelectedObjects.GetValue("U_DeliveryContent", 0).ToString());
                            }
                        }
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_F")//起运港承运人
                    {
                        dbds.SetValue("U_FreighterCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_FreighterName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        if (AVA_OBNO == "@AVA_FF_OBNO")/*空运承运人 带到 主单发货人*/
                        {
                            SAPbouiCOM.DBDataSource dbds3 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3);
                            dbds3.SetValue("U_SenderCode", dbds3.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                            dbds3.SetValue("U_Sender", dbds3.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                        }
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_T")//船公司/航空公司
                    {
                        dbds.SetValue("U_TransportCardCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_TransportCardName", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_TD")//中转港代理
                    {
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO2);
                        dbds.SetValue("U_TranshipDelegateC", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds.SetValue("U_TranshipDelegate", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardFName", 0).ToString() : pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_MN")//主单通知人
                    {
                        SAPbouiCOM.DBDataSource dbds3 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3);
                        dbds3.SetValue("U_NotifierCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        string cardName = String.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString();
                        dbds3.SetValue("U_Notifier", dbds.Offset, cardName);
                        Utils.SelectAddressDetail(this.CurrentForm, "175", AVA_BNO3, "U_NotificationDatail", pVal.SelectedObjects.GetValue("CardCode", 0).ToString(), true);
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_MR")//主单收货人
                    {
                        SAPbouiCOM.DBDataSource dbds3 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3);
                        dbds3.SetValue("U_ReceiverCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        string cardName = String.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString();
                        dbds3.SetValue("U_Receiver", dbds.Offset, cardName);
                        Utils.SelectAddressDetail(this.CurrentForm, "173", AVA_BNO3, "U_ReceiverDetail", pVal.SelectedObjects.GetValue("CardCode", 0).ToString(), true);
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_MS")//主单发货人
                    {
                        SAPbouiCOM.DBDataSource dbds3 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3);
                        dbds3.SetValue("U_SenderCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        string cardName = String.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString();
                        dbds3.SetValue("U_Sender", dbds.Offset, cardName);
                        Utils.SelectAddressDetail(this.CurrentForm, "171", AVA_BNO3, "U_SendDetail", pVal.SelectedObjects.GetValue("CardCode", 0).ToString(), true);
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_SN")//分单通知人
                    {
                        SAPbouiCOM.DBDataSource dbds4 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4);
                        dbds4.SetValue("U_NotifierCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        string cardName = String.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString();
                        dbds4.SetValue("U_Notifier", dbds.Offset, cardName);
                        Utils.SelectAddressDetail(this.CurrentForm, "1000079", AVA_BNO4, "U_NotificationDatail", pVal.SelectedObjects.GetValue("CardCode", 0).ToString(), true);
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_SR")//分单收货人
                    {
                        SAPbouiCOM.DBDataSource dbds4 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4);
                        dbds4.SetValue("U_ReceiverCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        string cardName = String.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString();
                        dbds4.SetValue("U_Receiver", dbds.Offset, cardName);
                        Utils.SelectAddressDetail(this.CurrentForm, "1000081", AVA_BNO4, "U_ReceiverDetail", pVal.SelectedObjects.GetValue("CardCode", 0).ToString(), true);
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_SS")//分单发货人
                    {
                        SAPbouiCOM.DBDataSource dbds4 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4);
                        dbds4.SetValue("U_SenderCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        string cardName = String.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString();
                        dbds4.SetValue("U_Sender", dbds.Offset, cardName);
                        Utils.SelectAddressDetail(this.CurrentForm, "1000083", AVA_BNO4, "U_SendDetail", pVal.SelectedObjects.GetValue("CardCode", 0).ToString(), true);
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_N2")//分单通知人
                    {
                        SAPbouiCOM.DBDataSource dbds4 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4);
                        dbds4.SetValue("U_NotifierCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        string cardName = String.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString();
                        dbds4.SetValue("U_Notifier", dbds.Offset, cardName);
                        dbds4.SetValue("U_NotificationDatail", dbds.Offset, pVal.SelectedObjects.GetValue("U_DeliveryContent", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_R2")//分单收货人
                    {
                        SAPbouiCOM.DBDataSource dbds4 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4);
                        dbds4.SetValue("U_ReceiverCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        string cardName = String.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString();
                        dbds4.SetValue("U_Receiver", dbds.Offset, cardName);
                        dbds4.SetValue("U_ReceiverDetail", dbds.Offset, pVal.SelectedObjects.GetValue("U_DeliveryContent", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_S2")//分单发货人
                    {
                        SAPbouiCOM.DBDataSource dbds4 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4);
                        dbds4.SetValue("U_SenderCode", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        string cardName = String.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString().Trim()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString();
                        dbds4.SetValue("U_Sender", dbds.Offset, cardName);
                        dbds4.SetValue("U_SendDetail", dbds.Offset, pVal.SelectedObjects.GetValue("U_DeliveryContent", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_PORT_S")
                    {
                        dbds.SetValue("U_StartPortCode", dbds.Offset, pVal.SelectedObjects.GetValue("DocEntry", 0).ToString());
                        dbds.SetValue("U_StartPortThCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortCode", 0).ToString());
                        dbds.SetValue("U_StartPort", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortNameE", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_PORT_E")
                    {
                        dbds.SetValue("U_EndPortCode", dbds.Offset, pVal.SelectedObjects.GetValue("DocEntry", 0).ToString());
                        dbds.SetValue("U_EndPortThCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortCode", 0).ToString());
                        dbds.SetValue("U_EndPort", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortNameE", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCRD_TD")//中转港代理
                    {
                        SAPbouiCOM.DBDataSource dbds4 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO2);
                        dbds4.SetValue("U_TranshipDelegateC", dbds.Offset, pVal.SelectedObjects.GetValue("CardCode", 0).ToString());
                        dbds4.SetValue("U_TranshipDelegate", dbds.Offset, string.IsNullOrEmpty(pVal.SelectedObjects.GetValue("CardFName", 0).ToString()) ? pVal.SelectedObjects.GetValue("CardName", 0).ToString() : pVal.SelectedObjects.GetValue("CardFName", 0).ToString());
                    }
                    /*货物信息*/
                    else if (pVal.ChooseFromListUID == "CFL_Cargo")
                    {
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO1);
                        dbds.SetValue("U_CargoCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_CargoCode", 0).ToString());
                        dbds.SetValue("U_CargoName", dbds.Offset, pVal.SelectedObjects.GetValue("U_DescriptionC", 0).ToString());
                        dbds.SetValue("U_CargoEName", dbds.Offset, pVal.SelectedObjects.GetValue("U_DescriptionE", 0).ToString());
                    }
                    /*中转港*/
                    else if (pVal.ChooseFromListUID == "CFL_PORT_T")
                    {
                        dbds.SetValue("U_TrsferPortCode", dbds.Offset, pVal.SelectedObjects.GetValue("DocEntry", 0).ToString());
                        dbds.SetValue("U_TrsferPortThCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortCode", 0).ToString());
                        dbds.SetValue("U_TrsferPort", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortNameE", 0).ToString());
                        //dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO2);
                        //dbds.SetValue("U_TranshipPortCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_CityCode", 0).ToString());
                        //dbds.SetValue("U_TranshipPortName", dbds.Offset, pVal.SelectedObjects.GetValue("U_CityNameE", 0).ToString());
                        //dbds.SetValue("U_TranshipStateCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_CountryCode", 0).ToString());
                        //dbds.SetValue("U_TranshipStateName", dbds.Offset, pVal.SelectedObjects.GetValue("U_CountryNameE", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_Dgous")
                    {
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO1);
                        dbds.SetValue("U_DangerPro", dbds.Offset, pVal.SelectedObjects.GetValue("U_DCName", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_ODCM")
                    {
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO1);
                        dbds.SetValue("U_DangerPro", dbds.Offset, pVal.SelectedObjects.GetValue("U_DCName", 0).ToString());
                    }
                    else if (pVal.ChooseFromListUID == "CFL_PORT_2")//中转港
                    {
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO2);
                        dbds.SetValue("U_PortCode", dbds.Offset, pVal.SelectedObjects.GetValue("DocEntry", 0).ToString());
                        dbds.SetValue("U_TranshipPortCode", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortCode", 0).ToString());
                        dbds.SetValue("U_TranshipPortName", dbds.Offset, pVal.SelectedObjects.GetValue("U_PortNameE", 0).ToString());
                    }
                    /*快递公司*/
                    else if (pVal.ChooseFromListUID == "CFL_ExpressCmp")
                    {
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO5);
                        dbds.SetValue("U_ExpressCmp", dbds.Offset, pVal.SelectedObjects.GetValue("CardName", 0).ToString());
                    }
                    /*主单*/
                    else if (pVal.ChooseFromListUID == "CFL_MBL")
                    {
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                        int UseCount = 0;
                        if (int.TryParse(pVal.SelectedObjects.GetValue("U_UseCount", 0).ToString(), out UseCount))
                        {
                            string MBLNumber = string.Format("{0}-{1}", pVal.SelectedObjects.GetValue("U_AirlineCode", 0), pVal.SelectedObjects.GetValue("U_OrderNumber", 0));
                            if (UseCount > 1)
                            {
                                if (SBOApp.MessageBox("主单号：" + MBLNumber + " 已使用 " + UseCount.ToString() + " 次。\r\n是否继续使用？", 1, "是", "否") == 1)
                                {
                                    dbds.SetValue("U_MBLEntry", dbds.Offset, pVal.SelectedObjects.GetValue("DocEntry", 0));
                                    dbds.SetValue("U_MBLNumber", dbds.Offset, MBLNumber);
                                }
                            }
                            else
                            {
                                dbds.SetValue("U_MBLEntry", dbds.Offset, pVal.SelectedObjects.GetValue("DocEntry", 0));
                                dbds.SetValue("U_MBLNumber", dbds.Offset, MBLNumber);
                            }
                        }
                    }
                    //指定客服（员工）
                    else if (pVal.ChooseFromListUID == "CFL_Employee")
                    {
                        pVal.AutoFillValue = false;
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                        string ServiceName = pVal.SelectedObjects.GetValue("jobTitle", 0).ToString();
                        if (string.IsNullOrEmpty(ServiceName))
                            ServiceName = pVal.SelectedObjects.GetValue("firstName", 0) + pVal.SelectedObjects.GetValue("lastName", 0);
                        dbds.SetValue("U_ServiceName", dbds.Offset, ServiceName);
                        //if (CurrentForm.Mode == BoFormMode.fm_OK_MODE || CurrentForm.Mode == BoFormMode.fm_VIEW_MODE)
                        //{
                        //    CurrentForm.Mode = BoFormMode.fm_UPDATE_MODE;
                        //}byWangPeng 2012年8月14日 18:34:58
                    }
                    //业务员
                    else if (pVal.ChooseFromListUID == "CFL_SalesPerson")
                    {
                        pVal.AutoFillValue = false;
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                        dbds.SetValue("U_BusinessMan", dbds.Offset, pVal.SelectedObjects.GetValue("SlpName", 0).ToString());
                        dbds.SetValue("U_BnsManCode", dbds.Offset, pVal.SelectedObjects.GetValue("SlpCode", 0).ToString());
                        //if (CurrentForm.Mode == BoFormMode.fm_OK_MODE || CurrentForm.Mode == BoFormMode.fm_VIEW_MODE)
                        //{
                        //    CurrentForm.Mode = BoFormMode.fm_UPDATE_MODE;
                        //}  byWangPeng 2012年8月14日 18:34:58
                    }
                    else if (pVal.ChooseFromListUID == "CFL_Operator")
                    {
                        pVal.AutoFillValue = false;
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                        string Operator = pVal.SelectedObjects.GetValue("jobTitle", 0).ToString();
                        if (string.IsNullOrEmpty(Operator))
                        {
                            Operator = pVal.SelectedObjects.GetValue("firstName", 0).ToString().Trim() + pVal.SelectedObjects.GetValue("lastName", 0).ToString().Trim();
                            SBOApp.SetStatusBarMessage("英文名称不存在！", BoMessageTime.bmt_Short, false);
                        }
                        dbds.SetValue("U_Operator", dbds.Offset, Operator);
                        dbds.SetValue("U_OperatorCode", dbds.Offset, pVal.SelectedObjects.GetValue("empID", 0).ToString());
                        Utils.SelectShowEmpId(dbds, Operator, false);
                    }
                    else if (pVal.ChooseFromListUID == "CFL_OCPR")
                    {
                        dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                        dbds.SetValue("U_CntctCode", dbds.Offset, pVal.SelectedObjects.GetValue("Name", 0).ToString().Trim());
                    }
                }
                #endregion
                if (CurrentForm.Mode == BoFormMode.fm_OK_MODE || CurrentForm.Mode == BoFormMode.fm_VIEW_MODE)
                {
                    CurrentForm.Mode = BoFormMode.fm_UPDATE_MODE;
                }
            }
        }

        void B1Form_BusinessOperation_Base_frm_FormDataEvent(SAPBoAddon.B1AddonBase.B1BusinessObjectInfo pVal, ref bool BubbleEvent)
        {
            if (pVal.BeforeAction)
            {
                if (pVal.EventType == BoEventTypes.et_FORM_DATA_LOAD)
                {
                    //关闭相关联的子窗体
                    CloseSonForms();
                }
                if (pVal.EventType == BoEventTypes.et_FORM_DATA_ADD || pVal.EventType == BoEventTypes.et_FORM_DATA_UPDATE)
                {
                    //检查单据状态为“作废”时，是否有费用存在
                    CheckChargeOrderExist(ref BubbleEvent);
                }
            }
            else
            {
                if (pVal.EventType == BoEventTypes.et_FORM_DATA_LOAD && pVal.ActionSuccess)
                {
                    ClearUserDateSource();
                    CloseSonForms();
                    #region 显示行号
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO1, 0);/*货物显示行号、总行数*/
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO2, 0, "TnsLine", "TnsTal"); /*中转港显示行号、总行数*/
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO5, 0, "FileLine", "FileTal"); /*附件显示行号、总行数*/
                    #endregion
                    //this.RecordSerialNumInUds(); /*记录流水号*///添加在此处在第二次添加单据时，会一直提示回收前一个流水号，因在保存为又把原始单据加载出来。
                    #region 设置状态控件是否可编辑  由BeforAction里移动来的  by WangPeng 2012年8月29日 10:25:32//Vincent.yin
                    //if ((this.FormSetting.FormModeSetting.DisableStatus as string[]).Contains<string>(this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).GetValue("U_Status", 0).Trim()))//如果不可编辑
                    //{
                    //}
                    //else
                    //{
                    //    SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, new string[] { "7" }, true);
                    //}
                    #endregion
                }
                if ((pVal.EventType == BoEventTypes.et_FORM_DATA_ADD || pVal.EventType == BoEventTypes.et_FORM_DATA_UPDATE) && pVal.ActionSuccess)//主对象保存成功之后
                {
                    //AddSons();
                    //更新所有来源委托单的状态为“已结算”——by Webb.Wen at 2012-03-06 11:12:17
                    UpdateSourceOrderStatus();
                }
                #region 上传附件
                /*上传附件*/
                if (pVal.EventType == BoEventTypes.et_FORM_DATA_ADD || pVal.EventType == BoEventTypes.et_FORM_DATA_UPDATE)
                {
                    try
                    {
                        Common_UpLoad oUpLoad = new Common_UpLoad();
                        oUpLoad.Uploading(CurrentForm, AVA_BNO5);
                        oUpLoad.DownButtonVisable(CurrentForm, AVA_BNO5, FileCurrentOffset, false);
                    }
                    catch (Exception ex)
                    {
                        SBOApp.SetStatusBarMessage("更新失败！错误信息：" + ex.Message, BoMessageTime.bmt_Short, false);
                        BubbleEvent = false;
                        CurrentForm.Mode = BoFormMode.fm_UPDATE_MODE;
                    }
                }
                #endregion

                if (pVal.EventType == BoEventTypes.et_FORM_DATA_UPDATE)
                {
                    this.RefreshSerNum();
                }
            }
        }

        void B1Form_BusinessOperation_Base_frm_ItemEvent(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            if (pVal.Before_Action)
            {
                #region 事件前
                #region CheckBox点击事件（即使是Before_Action，CheckBox.Checked的状态变化也是在事件之前）
                if (pVal.EventType == BoEventTypes.et_ITEM_PRESSED && CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Split(':')[0] == pVal.ItemUID) != null)
                {
                    string thisDocEntry = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).GetValue("DocEntry", 0).Trim();
                    if (thisDocEntry.Trim().Length > 0)
                    {
                        ClickSonCheckBox(pVal, ref BubbleEvent);
                    }
                }
                #endregion
                #region Label点击事件
                if (pVal.EventType == BoEventTypes.et_DOUBLE_CLICK && CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Split(':')[1] == pVal.ItemUID) != null)
                {
                    if (CurrentFormEx.Mode == BoFormMode.fm_ADD_MODE)
                    {
                        SBOApp.MessageBox("请先保存业务单再进行子单据的处理!");
                        return;
                    }
                    string thisDocEntry = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).GetValue("DocEntry", 0).Trim();
                    if (thisDocEntry.Trim().Length > 0)
                    {
                        ClickSonLabel(pVal);
                    }
                }
                #endregion

                //当某业务单中的某个页面为打开状态，当关闭此业务单时，应提示还有没有关闭的内含页面。关闭后才能关闭整个业务单。
                if (pVal.EventType == BoEventTypes.et_FORM_CLOSE)
                {
                    List<string> sonForms = CloseSonForms(false);
                    if (sonForms.Count > 0)
                    {
                        foreach (var item in sonForms)
                        {
                            if (SBOApp.Forms.Item(item).Mode == BoFormMode.fm_OK_MODE)
                            {
                                SBOApp.Forms.Item(item).Close();
                            }
                            else
                            {
                                SBOApp.MessageBox("当前业务单还有未关闭的子窗体");
                                SBOApp.Forms.Item(item).Visible = true;
                                BubbleEvent = false;
                            }
                        }
                    }
                }
                #endregion
            }
            else
            {
                #region
                if (pVal.ItemUID == "1" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED && this.CurrentForm.Mode == BoFormMode.fm_ADD_MODE && pVal.ActionSuccess)
                {
                    CloseSonForms();
                }
                #region switch panel

                if (pVal.ItemUID == "tab_5" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CurrentForm.PaneLevel = 6;
                    #region 是否存在附件
                    Common_UpLoad Uploading = new Common_UpLoad();
                    Uploading.DownButtonVisable(CurrentForm, AVA_BNO5, FileCurrentOffset);
                    #endregion
                }
                #endregion
                if (pVal.EventType == BoEventTypes.et_FORM_CLOSE)
                {
                    CloseSonForms();
                }
                #endregion
                #region 自定义LinkButton
                if (new string[] { "1000038"/*接货地代码*/, "1000008"/*起运港口代码*/, "1000009"/*目的港口代码*/, "440", "324"/*中转港口代码*/ }.Contains<string>(pVal.ItemUID) && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.OpenUserDeFinedObjectForm(this.CurrentForm, pVal.ItemUID, "AVA_FF_Port");
                }
                //基本凭证
                if (pVal.ItemUID == "377" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);

                    string BaseType = dbds.GetValue("U_BaseType", dbds.Offset).Trim();
                    if (string.IsNullOrEmpty(BaseType) || BaseType.EndsWith("Delegate"))
                    {
                        Utils.OpenUserDeFinedObjectForm(this.CurrentForm, pVal.ItemUID, BaseType, this.ShowForm);
                    }
                    else
                    {
                        Utils.OpenUserDeFinedObjectForm(this.CurrentForm, pVal.ItemUID, BaseType, this.ShowForm);
                    }
                }
                //主单管理
                if (pVal.ItemUID == "linkbtnMBL" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.OpenUserDeFinedObjectForm(this.CurrentForm, pVal.ItemUID, AVA_AirOrder);
                }
                #endregion
                #region 统一货物表的单位和统计总计的单位（by Webb.Wen at 2012-06-14 12:31:02）  这个事件控制写的太宽泛
                if (pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT && pVal.ItemChanged)
                {
                    Utils.SyncUnit(this.CurrentForm, pVal.ItemUID, this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO1), this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO));
                }
                #endregion
                #region 货物的添加及删除
                if (pVal.ItemUID == "cargo_42" && pVal.EventType == SAPbouiCOM.BoEventTypes.et_COMBO_SELECT && pVal.ItemChanged)
                {
                    DBDataSource dbds1 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO1);
                    if (dbds1.Offset == 0)
                    {
                        DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                        dbds.SetValue("U_CargoValueUnit", 0, dbds1.GetValue("U_Currency", 0));
                    }
                }
                #region Linq+Lambda的总体积计算
                if (pVal.EventType == BoEventTypes.et_COMBO_SELECT && new string[] { "cargo_32", "cargo_34" }.Contains<string>(pVal.ItemUID))
                {
                    Utils.CalculateVolumeAndQuantity(SBOApp, SBOCompany, CurrentForm, AVA_BNO1, CargoCurrentOffset);
                    Utils.MaterialSum(this.CurrentForm, AVA_OBNO, AVA_BNO1);
                }
                if (pVal.ItemUID == "cargo_24" && pVal.EventType == BoEventTypes.et_VALIDATE)
                {
                    Utils.CalculateVolumeAndQuantity(SBOApp, SBOCompany, CurrentForm, AVA_BNO1, CargoCurrentOffset);
                    Utils.MaterialSum(this.CurrentForm, AVA_OBNO, AVA_BNO1);
                }
                #endregion
                #region  货物信息
                //上一条
                if (pVal.ItemUID == "CaPrevious" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CargoCurrentOffset = Utils.Previous(SBOApp, pVal.FormUID, AVA_BNO1);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO1, CargoCurrentOffset);/*货物显示行号、总行数*/
                }
                //下一条
                if (pVal.ItemUID == "CargoNext" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CargoCurrentOffset = Utils.Next(SBOApp, pVal.FormUID, AVA_BNO1);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO1, CargoCurrentOffset);/*货物显示行号、总行数*/
                }
                //添加
                if (pVal.ItemUID == "CargoAdd" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CargoCurrentOffset = Utils.Add(SBOApp, pVal.FormUID, AVA_BNO1);
                    //下拉列表框的默认值
                    Utils.ComboBox_Cargo_SelectDefault(this.CurrentForm, Cargo_ComboBoxUID_Field, AVA_BNO1);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO1, CargoCurrentOffset);/*货物显示行号、总行数*/
                }
                //删除
                if (pVal.ItemUID == "CargoDel" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    CargoCurrentOffset = Utils.Delete(SBOApp, pVal.FormUID, AVA_BNO1, CargoCurrentOffset);
                    Utils.MaterialSum(this.CurrentForm, AVA_OBNO, AVA_BNO1);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO1, CargoCurrentOffset);/*货物显示行号、总行数*/
                }
                //控件失去焦点-计算货物相关的总计
                if (CargoInfoSumItem.Contains(pVal.ItemUID) && pVal.EventType == BoEventTypes.et_VALIDATE)//&& pVal.ItemChanged by WangPeng
                {
                    Utils.MaterialSum(this.CurrentForm, AVA_OBNO, AVA_BNO1);
                    if (pVal.ItemUID == "cargo_10")/*计费重变化算计费总计 added by WangPeng 2012年8月2日 17:49:22*/
                    {
                        this.SBLFreightCharge(pVal.FormUID);
                    }
                }
                //浏览所有
                if (pVal.ItemUID == "CarSurvey" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.Survey(SBOApp, SBOCompany, pVal.FormUID, AVA_BNO1);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO1, CargoCurrentOffset);/*货物显示行号、总行数*/
                }
                #endregion
                #endregion
                #region  中转港信息
                //上一条
                if (pVal.ItemUID == "PtPrevious" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    PortCurrentOffset = Utils.Previous(SBOApp, pVal.FormUID, AVA_BNO2);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO2, PortCurrentOffset, "TnsLine", "TnsTal"); /*中转港显示行号、总行数*/
                }
                //下一条
                if (pVal.ItemUID == "PortNext" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    PortCurrentOffset = Utils.Next(SBOApp, pVal.FormUID, AVA_BNO2);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO2, PortCurrentOffset, "TnsLine", "TnsTal"); /*中转港显示行号、总行数*/
                }
                //添加
                if (pVal.ItemUID == "PortAdd" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    PortCurrentOffset = Utils.Add(SBOApp, pVal.FormUID, AVA_BNO2);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO2, PortCurrentOffset, "TnsLine", "TnsTal"); /*中转港显示行号、总行数*/
                }
                //删除
                if (pVal.ItemUID == "PortDel" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    PortCurrentOffset = Utils.Delete(SBOApp, pVal.FormUID, AVA_BNO2, PortCurrentOffset);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO2, PortCurrentOffset, "TnsLine", "TnsTal"); /*中转港显示行号、总行数*/
                }
                //浏览所有
                if (pVal.ItemUID == "PrtSurvey" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.Survey(SBOApp, SBOCompany, pVal.FormUID, AVA_BNO2);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO2, PortCurrentOffset, "TnsLine", "TnsTal"); /*中转港显示行号、总行数*/
                }
                #endregion
                #region  附件信息
                //上一条
                if (pVal.ItemUID == "FlPrevious" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    FileCurrentOffset = Utils.Previous(SBOApp, pVal.FormUID, AVA_BNO5);
                    Common_UpLoad Uploading = new Common_UpLoad();
                    Uploading.DownButtonVisable(CurrentForm, AVA_BNO5, FileCurrentOffset);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO5, FileCurrentOffset, "FileLine", "FileTal"); /*附件显示行号、总行数*/
                }
                //下一条
                if (pVal.ItemUID == "FileNext" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    FileCurrentOffset = Utils.Next(SBOApp, pVal.FormUID, AVA_BNO5);
                    Common_UpLoad Uploading = new Common_UpLoad();
                    Uploading.DownButtonVisable(CurrentForm, AVA_BNO5, FileCurrentOffset);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO5, FileCurrentOffset, "FileLine", "FileTal"); /*附件显示行号、总行数*/
                }
                //添加
                if (pVal.ItemUID == "FileAdd" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    FileCurrentOffset = Utils.Add(SBOApp, pVal.FormUID, AVA_BNO5);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO5, FileCurrentOffset, "FileLine", "FileTal"); /*附件显示行号、总行数*/
                }
                //删除
                if (pVal.ItemUID == "FileDel" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    FileCurrentOffset = Utils.Delete(SBOApp, pVal.FormUID, AVA_BNO5, FileCurrentOffset);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO5, FileCurrentOffset, "FileLine", "FileTal"); /*附件显示行号、总行数*/
                }
                //浏览所有
                if (pVal.ItemUID == "FleSurvey" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Utils.Survey(SBOApp, SBOCompany, pVal.FormUID, AVA_BNO5);
                    Utils.ShowDBDSNum(CurrentForm, AVA_BNO5, FileCurrentOffset, "FileLine", "FileTal"); /*附件显示行号、总行数*/
                }
                //选择文件路径
                if (pVal.ItemUID == "Upload" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    Common_UpLoad upload = new Common_UpLoad();
                    upload.SetAffixInfo(CurrentForm, AVA_BNO5, FileCurrentOffset);
                }
                //下载上传的文件
                if (pVal.ItemUID == "Down" && pVal.EventType == BoEventTypes.et_CLICK)
                {
                    Common_UpLoad Uploading = new Common_UpLoad();
                    Uploading.DownFile(CurrentForm, AVA_BNO5, FileCurrentOffset);
                }
                #endregion
                #region 主单、分单费用合计、付款方式
                //计算主单和分单的费用合计
                if (pVal.ItemChanged)
                {
                    if (MBLItemData.Contains(pVal.ItemUID))
                    {
                        MBLSum(pVal.FormUID);
                    }
                    if (MBLCharge.Contains(pVal.ItemUID))
                    {
                        MBLChargeSum(pVal.FormUID);
                    }
                    if (SBLItemData.Contains(pVal.ItemUID))
                    {
                        SBLSum(pVal.FormUID);
                    }
                    if (SBLCharge.Contains(pVal.ItemUID))
                    {
                        SBLChargeSum(pVal.FormUID);
                    }
                    //主单付款方式
                    if (pVal.ItemUID == "177" && pVal.FormTypeEx == "AVA_FF_BusinessOpera")
                    {
                        MBLChangeCharge(pVal.FormUID);
                    }
                    //主单其他付款方式
                    if (pVal.ItemUID == "179" && pVal.FormTypeEx == "AVA_FF_BusinessOpera")/*分清海运、空运吧，哥哥们，搞毛啊，fk*/
                    {
                        MBLOtherChangeCharge(pVal.FormUID);
                    }
                    //分单付款方式
                    if (pVal.ItemUID == "1000085" && pVal.FormTypeEx == "AVA_FF_BusinessOpera")
                    {
                        SBLChangeCharge(pVal.FormUID);
                    }
                    //分单其他付款方式
                    if (pVal.ItemUID == "1000087" && pVal.FormTypeEx == "AVA_FF_BusinessOpera")
                    {
                        SBLOtherChangeCharge(pVal.FormUID);
                    }
                    //主单费用总价
                    if (pVal.ItemUID == "85" || pVal.ItemUID == "187")
                    {
                        MBLFreightCharge(pVal.FormUID);
                    }
                    //分单费用总价
                    if (pVal.ItemUID == "85" || pVal.ItemUID == "1000095")
                    {
                        SBLFreightCharge(pVal.FormUID);
                    }
                }

                #endregion
                #region 制作费用  账单列表
                /*制作费用按钮单击*/
                if (pVal.ItemUID == "btn_Fee" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED && this.CurrentForm.Mode == BoFormMode.fm_OK_MODE)
                {
                    this.ShowForm(B1FormTypes.ado_AVA_FF_CreateCost, this.CurrentForm.UniqueID);
                }
                /*账单列表*/
                if (pVal.ItemUID == "btn_VcList" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED && this.CurrentForm.Mode == BoFormMode.fm_OK_MODE)
                {
                    this.ShowForm(B1FormTypes.ado_AVA_BO_VoucherList, this.CurrentForm.UniqueID);
                }

                #endregion
                #region 业务伙地址信息
                #region 主单
                if (pVal.ItemUID == "btn_425" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    string cardcode = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3).GetValue("U_SenderCode", 0).Trim();
                    Utils.SelectAddressDetail(this.CurrentForm, "171", AVA_BNO3, "U_SendDetail", cardcode);
                }
                if (pVal.ItemUID == "btn_426" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    string cardcode = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3).GetValue("U_ReceiverCode", 0).Trim();
                    Utils.SelectAddressDetail(this.CurrentForm, "173", AVA_BNO3, "U_ReceiverDetail", cardcode);
                }
                if (pVal.ItemUID == "btn_427" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    string cardcode = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3).GetValue("U_NotifierCode", 0).Trim();
                    Utils.SelectAddressDetail(this.CurrentForm, "175", AVA_BNO3, "U_NotificationDatail", cardcode);
                }
                #endregion
                #region 分单
                if (pVal.ItemUID == "btn_428" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    string cardcode = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4).GetValue("U_SenderCode", 0).Trim();
                    Utils.SelectAddressDetail(this.CurrentForm, "1000083", AVA_BNO4, "U_SendDetail", cardcode);
                }
                if (pVal.ItemUID == "btn_429" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    string cardcode = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4).GetValue("U_ReceiverCode", 0).Trim();
                    Utils.SelectAddressDetail(this.CurrentForm, "1000081", AVA_BNO4, "U_ReceiverDetail", cardcode);
                }
                if (pVal.ItemUID == "btn_430" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                {
                    string cardcode = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4).GetValue("U_NotifierCode", 0).Trim();
                    Utils.SelectAddressDetail(this.CurrentForm, "1000079", AVA_BNO4, "U_NotificationDatail", cardcode);
                }
                #endregion
                #endregion
                #region ETD/ETA/ATA
                //当录入ETD时，ATD能不能自动默认为ETD时间（又取消了）
                //if (pVal.ItemUID == "99" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                //{
                //    DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                //    string ETD = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, pVal.ItemUID).ToString();

                //    dbds.SetValue("U_ETD", dbds.Offset, ETD);
                //    dbds.SetValue("U_ATD", dbds.Offset, ETD);
                //}
                //if (pVal.ItemUID == "103" && pVal.EventType == BoEventTypes.et_ITEM_PRESSED)
                //{
                //    DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                //    string ETA = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, pVal.ItemUID).ToString();
                //    dbds.SetValue("U_ETA", dbds.Offset, ETA);
                //    dbds.SetValue("U_ATA", dbds.Offset, ETA);
                //}
                #endregion
                #region 手动填写主分单收发货人的时候，联动主分单页面
                if (pVal.ItemChanged && new string[] { "113", "129", "117", "109", "1000015", "1000017", "1000019" }.Contains<string>(pVal.ItemUID))
                {
                    SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                    SAPbouiCOM.DBDataSource dbds3 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3);
                    if (AVA_OBNO == "@AVA_FF_OBNO")/*空运 主单发货人 取自 承运人；海运则取自 起运港代理*/
                    {
                        if (pVal.ItemUID == "129")/*承运人*/
                        {
                            dbds3.SetValue("U_SenderCode", dbds3.Offset, dbds.GetValue("U_FreighterCode", dbds.Offset));
                            dbds3.SetValue("U_Sender", dbds3.Offset, dbds.GetValue("U_FreighterName", dbds.Offset));
                        }
                    }
                    else
                    {
                        if (pVal.ItemUID == "113")/*起运港代理*/
                        {
                            dbds3.SetValue("U_SenderCode", dbds3.Offset, dbds.GetValue("U_StartDelegateCode", dbds.Offset));
                            dbds3.SetValue("U_Sender", dbds3.Offset, dbds.GetValue("U_StartDelegateName", dbds.Offset));
                        }
                    }
                    if (pVal.FormTypeEx == B1FormTypes.ado_AVA_SE_BusinessOperation)
                    {
                        #region 海运业务单部分字段同步 （这特么的谁之前加的Swith-case,不知道区分海运、空运、陆运么，靠）
                        switch (pVal.ItemUID)
                        {
                            case "117":
                                dbds3.SetValue("U_ReceiverCode", dbds.Offset, dbds.GetValue("U_EndDelegateCode", dbds.Offset));
                                dbds3.SetValue("U_Receiver", dbds.Offset, dbds.GetValue("U_EndDelegateName", dbds.Offset));
                                break;
                            case "109":
                                dbds3.SetValue("U_NotifierCode", dbds.Offset, dbds.GetValue("U_DelegateCardCode", 0).ToString());
                                dbds3.SetValue("U_Notifier", dbds.Offset, dbds.GetValue("U_DelegateCardName", 0).ToString());
                                break;
                            case "1000015"://本来基础信息页签绑定的就是子表
                                break;
                            case "1000017":
                                break;
                            case "1000019":
                                break;
                        }
                        #endregion
                    }

                }
                #endregion
                #region 单据编码
                if (pVal.ItemUID == "45" && pVal.EventType == BoEventTypes.et_COMBO_SELECT && pVal.ItemChanged)
                {
                    if (pVal.FormMode == 2)//更新状态
                        SerialNumber.GetInstance().RecordSerialNumInUds(CurrentForm); //当单据类型发生变化时，给窗体的变量赋值。
                    SerialNumber.GetInstance().GetSerialNumberByProc(CurrentForm);
                }
                #endregion

                #region 分单号默认大写
                if (this.CurrentForm.Mode != BoFormMode.fm_OK_MODE)
                {
                    if (pVal.EventType == BoEventTypes.et_LOST_FOCUS && pVal.ItemUID == "1000014")
                    {
                        this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_SBLNumber", 0, this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).GetValue("U_SBLNumber", 0).ToUpper());
                    }
                }
                #endregion
                if (pVal.ItemUID == "7" && pVal.ItemChanged)
                {
                    SAPbouiCOM.EditText oedt = CurrentForm.Items.Item("13").Specific;
                    oedt.Active = true;
                }
            }
        }
        #endregion

        #region override methods
        protected override bool BeforeSaveCheckFormData()
        {
            if (!Utils.CheckBusinessPartner(SBOApp, CurrentForm, AVA_OBNO, "U_CardName"))
            {
                return false;
            }
            if (this.CurrentForm.TypeEx != B1FormTypes.ado_AVA_LN_BusinessOperation) //陆运不需要验证"分单号"为空 added by WangPeng 2012年8月29日 18:24:39
            {
                if (!CheckSBLNumber())
                {
                    return false;
                }
            }

            return true;
        }
        protected override void FormEditModeChange(SAPBoAddon.frmItemEditMode frmEditMode)
        {
            switch (frmEditMode)
            {
                case SAPBoAddon.frmItemEditMode.fe_AddMode:
#if DEBUG
                    DateTime dt1;
                    DateTime dt2;
                    TimeSpan ts;
                    dt1 = DateTime.Now;
#endif

                    CurrentForm.Freeze(true);
                    //自动添加操作日期
                    SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                    /*操作员，客服相关*/
                    dynamic Operator = Utils.GetCurrentUser();
                    dbds.SetValue("U_Operator", dbds.Offset, Operator.Operator);
                    dbds.SetValue("U_OperatorCode", dbds.Offset, Operator.empID);
                    Utils.SelectShowEmpId(dbds, Operator.Operator, false);
                    //获取客服名称 added by WangPeng  2014年8月20日15:23:52
                    this.GetServiceName();

                    dbds.SetValue("U_DocDate", dbds.Offset, DateTime.Now.ToString("yyyyMMdd"));
                    dbds.SetValue("UserSign", dbds.Offset, SBOCompany.UserSignature.ToString());
                    #region ComboBox赋默认值
                    /*ComboBox选默认*/
                    this.ComboBox_SelectDefault();
                    //this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_SBLNumber", 0, GetSBLNumber());//2011-12-19 16:10:59
                    this.Matrix_AutoAddLine();
                    #endregion
                    //this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3).SetValue("U_NCV", 0, "N.C.V");
                    //this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3).SetValue("U_NVD", 0, "N.V.D");
                    //this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4).SetValue("U_NCV", 0, "N.C.V");
                    //this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4).SetValue("U_NVD", 0, "N.V.D");
                    CurrentForm.Freeze(false);

#if DEBUG
                    dt2 = DateTime.Now;
                    ts = dt2 - dt1;
                    SBOApp.StatusBar.SetText(string.Format("置换Add Mode,耗时:[{0}]", ts.TotalMilliseconds.ToString()), BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Success);
#endif
                    //SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, new string[] { "7" }, true);
                    break;

            }
            CloseSonForms();
            ClearUserDateSource();
            #region 显示行号
            Utils.ShowDBDSNum(CurrentForm, AVA_BNO1, 0);/*货物显示行号、总行数*/
            Utils.ShowDBDSNum(CurrentForm, AVA_BNO2, 0, "TnsLine", "TnsTal"); /*中转港显示行号、总行数*/
            Utils.ShowDBDSNum(CurrentForm, AVA_BNO5, 0, "FileLine", "FileTal"); /*附件显示行号、总行数*/
            #endregion
        }
        protected override void FormInfoSetting(SAPBoAddon.B1FormSetting FormSetting)
        {
            FormSetting.AutoGetObjectNextNumber = true;
            #region 控件是否可编辑
            string[] ItemList;
            string[] Items;
            string[] filter = new string[] { "btn_Send", "btn_Fee", "CaPrevious", "CargoNext", "CarSurvey", "PtPrevious", "PortNext", "PrtSurvey", "FlPrevious", "FileNext", "FleSurvey" };
            string[] FileItems = new String[] { "334", "340", "342", "344", "350", "336", "346", "352", "338", "348", "354", "356", "Upload", "FileAdd", "FileDel" };
            string[] NewModeItms = new string[] { "3", "7", "35", "378", "379", "417", "txtApp" };
            #region 添加状态
            FormSetting.FormModeSetting.itmNewModeEnable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, NewModeItms);
            FormSetting.FormModeSetting.itmNewModeDisable = NewModeItms;
            #endregion
            #region 浏览状态
            FormSetting.FormModeSetting.StatusItemUID = "7";
            SAPBoAddon.BrowseModeSetting BrowseModeSetting;
            #region P状态
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "P";
            //P状态下可编辑的状态
            BrowseModeSetting.itmBrowseModeEnable = Utils.GetFormItems(FormSetting.FormXmlDocument);
            //P状态下不可编辑的状态
            BrowseModeSetting.itmBrowseModeDisable = new string[] { "3", "35", "45", "378", "379", "417", "txtApp" };

            #endregion
            ItemList = new string[FileItems.Length + filter.Length];
            FileItems.CopyTo(ItemList, 0);
            filter.CopyTo(ItemList, FileItems.Length);
            #region A状态
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "A";
            Items = new string[FileItems.Length + 1];
            FileItems.CopyTo(Items, 0);
            Items[Items.Length - 1] = "7";
            BrowseModeSetting.itmBrowseModeEnable = Items;
            Items = new string[ItemList.Length + 1];
            ItemList.CopyTo(Items, 0);
            Items[Items.Length - 1] = "7";
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, Items);
            #endregion
            #region R状态
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "R";
            BrowseModeSetting.itmBrowseModeEnable = FileItems;
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, ItemList);
            #endregion
            #region C状态
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "C";
            //BrowseModeSetting.itmBrowseModeEnable = new string[] { "7" };
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, filter);
            #endregion
            #region D状态
            BrowseModeSetting = FormSetting.FormModeSetting.BrowseModeSettingList.Add();
            BrowseModeSetting.Status = "D";
            //BrowseModeSetting.itmBrowseModeEnable = new string[] { "7" };
            BrowseModeSetting.itmBrowseModeDisable = Utils.GetFormItems(FormSetting.FormXmlDocument, true, filter);
            #endregion
            #endregion
            #region 查找状态
            ItemList = Utils.GetFormItems(FormSetting.FormXmlDocument);
            FormSetting.FormModeSetting.itmFindModeEnable = ItemList;//查找状态可编辑的控件
            //FormSetting.FormModeSetting.itmFindModeDisable = ";//查找状态不可编辑的控件
            #endregion
            #endregion
        }
        protected override void InitializeForm(SAPBoAddon.B1FormInitializePar InitPar)
        {
#if DEBUG
            DateTime dt1;
            DateTime dt2;
            TimeSpan ts;
            dt1 = DateTime.Now;
#endif
            this.CurrentForm.Freeze(true);
            /*加载ComboBox可选项*/
            this.Combobox_Initialize();
            //加载用户
            Utils.LoadUser(this.CurrentForm, this.SBOCompany, "379");
            //审批人
            Utils.LoadUser(this.CurrentForm, this.SBOCompany, "txtApp");

            //得到领导名称显示在窗体上
            string empid = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).GetValue("U_Operator", 0);
            if (!string.IsNullOrEmpty(empid))
            {
                int empId = Convert.ToInt32(empid);
                //得到组别名称
                GetTeamLeaderNameInformation(empId);

            }

            if (!String.IsNullOrEmpty(InitPar.FatherFormUID) && new Regex(@"AVA_\w{2}_Delegate").Match(InitPar.FatherFormUID).Success)//如果父窗体是委托单，从委托单复制
            {
                SBOApp.StatusBar.SetText(String.Format("正在从委托单复制"), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                Utils.SetRemarkByItem(this.CurrentForm);
                //this.CurrentForm.Mode = BoFormMode.fm_ADD_MODE;
                SBOApp.Menus.Item(B1MenuTypes.sys_Add).Activate();

                CreateNewFromDelegateList(InitPar.FatherFormUID);
                SBOApp.StatusBar.SetText(String.Format("基于委托单复制成功！"), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
            }
            // 预告单 by WangPeng 2014年8月19日 11:56:29 AVA_FF_Prealert
            if (!String.IsNullOrEmpty(InitPar.FatherFormUID) && new Regex(@"AVA_\w{2}_Prealert").Match(InitPar.FatherFormUID).Success)//如果父窗体是预告单，从预告单复制
            {
                SBOApp.StatusBar.SetText(String.Format("正在从 预告单 复制.."), BoMessageTime.bmt_Long, BoStatusBarMessageType.smt_Warning);
                Utils.SetRemarkByItem(this.CurrentForm);
                //this.CurrentForm.Mode = BoFormMode.fm_ADD_MODE;
                SBOApp.Menus.Item(B1MenuTypes.sys_Add).Activate();

                CopyFromPrealert(InitPar.FatherFormUID);
                SBOApp.StatusBar.SetText(String.Format("基于预告单 复制成功！"), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
            }
            //从到港复制
            if (!String.IsNullOrEmpty(InitPar.FatherFormUID) && InitPar.FatherFormUID.Contains("_ArrivePort"))
            {
                SBOApp.StatusBar.SetText(String.Format("正在从到港复制"), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                CopyFromArrivePort(InitPar.FatherFormUID);
                SBOApp.StatusBar.SetText(String.Format("基于到港复制成功！"), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);

            }
            //续程生成新单据
            if (!String.IsNullOrEmpty(InitPar.FatherFormUID) && InitPar.FatherFormUID.Contains("AVA_FF_BusinessOpera"))
            {
                SBOApp.StatusBar.SetText(String.Format("正在生成续程单据"), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                CopyFromOperaGoOnPort(InitPar.FatherFormUID);
                SBOApp.StatusBar.SetText(String.Format("续程单据生成成功！"), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);

            }
            if (InitPar.FatherFormUID.Contains("AVA_FF_AirOrderUsed"))  //by WangPeng 2012年9月18日 16:43:48
            {
                SBOApp.StatusBar.SetText(String.Format("正在从[主单领用]复制..."), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Warning);
                this.CopyFromAirOrderUsed(InitPar.FatherFormUID);
                SBOApp.StatusBar.SetText(String.Format("基于[主单领用]复制成功."), BoMessageTime.bmt_Short, BoStatusBarMessageType.smt_Success);
            }

            if (!String.IsNullOrEmpty(InitPar.FatherFormUID) && new Regex(@"\b\d+\b").Match(InitPar.FatherFormUID).Success)
            {
                this.CurrentForm.Mode = SAPbouiCOM.BoFormMode.fm_FIND_MODE;
                SAPBoAddon.B1Assistant.Item.SetValue(this.CurrentForm, this.CurrentForm.DataBrowser.BrowseBy, InitPar.FatherFormUID);
                this.CurrentForm.Items.Item("1").Click(SAPbouiCOM.BoCellClickType.ct_Regular);
            }
            this.CurrentForm.Freeze(false);
#if DEBUG
            dt2 = DateTime.Now;
            ts = dt2 - dt1;
            SBOApp.StatusBar.SetText(string.Format("窗体加载完成,耗时:[{0}]", ts.TotalMilliseconds.ToString()), BoMessageTime.bmt_Medium, BoStatusBarMessageType.smt_Success);
#endif
        }
        #endregion

        #region private methods
        /// <summary>
        /// 验证分单号
        /// </summary>
        /// <returns></returns>
        private bool CheckSBLNumber()
        {
            if (CurrentForm.Mode != BoFormMode.fm_ADD_MODE) return true;
            string sbl = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).GetValue("U_SBLNumber", 0).Trim();
            if (sbl.Length == 0)
            {
                SBOApp.MessageBox("分单号不能为空！");
                return false;
            }
            Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            rs.DoQuery(String.Format("select count(*) as C from [" + AVA_OBNO + "] where U_Status <> 'D' And U_SBLNumber='{0}'", sbl));
            if (rs.Fields.Item("C").Value != 0)
            {
                SBOApp.MessageBox(String.Format("分单号不能重复，分单号'{0}'已经存在", sbl), 1, "OK");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 获取DBDS的Offset
        /// </summary>
        /// <param name="omtx"></param>
        /// <param name="dbds"></param>
        /// <param name="MtxcurrentRow"></param>
        /// <returns></returns>
        private int GetDBDSOffSet(SAPbouiCOM.Matrix omtx, SAPbouiCOM.DBDataSource dbds, int MtxcurrentRow)
        {
            string keyVal = SAPBoAddon.B1Assistant.Matrix.GetCellValue(omtx, "col_LineId", MtxcurrentRow).ToString().Trim();
            string dbdsLineVal = string.Empty;
            for (int i = 0; i < dbds.Size; i++)
            {
                dbdsLineVal = dbds.GetValue("LineId", i).Trim();
                if (keyVal.Equals(dbdsLineVal))
                {
                    return i;
                }
            }
            return -1;
        }
        private void CopyFromPrealert(string fatherFormUID)
        {
            this.CurrentForm.Mode = BoFormMode.fm_ADD_MODE;

            Form fatherForm = SBOApp.Forms.Item(fatherFormUID);
            string FatherEntry = fatherForm.DataSources.DBDataSources.Item(AVA_OPRE).GetValue("DocEntry", 0);
            //string BaseSerial = fatherForm.DataSources.DBDataSources.Item(AVA_OPRE).GetValue("DocEntry", 0);

            this.CurrentForm.DataSources.UserDataSources.Item("BaseEntry").Value = FatherEntry;//指向父窗体
            this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value = fatherFormUID;//指向父窗体

            string[] array_tableName = { AVA_OBNO, AVA_BNO1, AVA_BNO2, AVA_BNO3, AVA_BNO4, AVA_BNO5 };
            DBDataSource dbds_BO = default(DBDataSource), dbds_Prealert = default(DBDataSource);
            string FieldName = string.Empty;
            foreach (var tableName in array_tableName)
            {
                dbds_BO = this.CurrentForm.DataSources.DBDataSources.Item(tableName);
                dbds_Prealert = fatherForm.DataSources.DBDataSources.Item(tableName.Replace("BNO", "PRE"));
                for (int i = 0; i < dbds_BO.Fields.Count; i++)
                {
                    FieldName = dbds_BO.Fields.Item(i).Name;
                    if (FieldName.IndexOf("U_") > -1 && FieldName.ToUpper() != "U_TEMP")
                    {
                        dbds_BO.SetValue(FieldName, dbds_BO.Offset, dbds_Prealert.GetValue(FieldName, dbds_Prealert.Offset));
                    }
                }
            }
            #region 获取父单据的业务类型，流水号赋值
            Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string onnm = String.Format("select AutoKey from ONNM WITH(UPDLOCK) where ObjectCode = '{0}'", "AVA_" + BusinessType + "_BusinessOpera");
            rs.DoQuery(onnm);
            this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("DocEntry", 0, rs.Fields.Item("AutoKey").Value.ToString());

            SerialNumber.GetInstance().GetSerialNumberByProc(this.CurrentForm);
            this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_BaseType", 0, fatherForm.TypeEx);
            this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_BaseEntry", 0, FatherEntry);
            #endregion


        }


        /// <summary>
        /// 从委托单复制
        /// </summary>
        /// <param name="odlg_formuid">委托单窗体</param>
        /// <param name="odlg_entry">委托单DocEntry</param>
        private void CopyFromDelegate(string odlg_formuid)
        {
            this.CurrentForm.Mode = BoFormMode.fm_ADD_MODE;
            DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
            Form fatherForm = SBOApp.Forms.Item(odlg_formuid);
            string odlg_entry = fatherForm.DataSources.DBDataSources.Item(AVA_ODLG).GetValue("DocEntry", 0);
            string BaseSerial = fatherForm.DataSources.DBDataSources.Item(AVA_ODLG).GetValue("DocEntry", 0);

            this.CurrentForm.DataSources.UserDataSources.Item("BaseEntry").Value = odlg_entry;//指向父窗体
            this.CurrentForm.DataSources.UserDataSources.Item("ParentUID").Value = odlg_formuid;//指向父窗体

            Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string onnm = String.Format("select AutoKey from ONNM WITH(UPDLOCK) where ObjectCode = '{0}'", "AVA_" + BusinessType + "_BusinessOpera");
            rs.DoQuery(onnm);
            this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("DocEntry", 0, rs.Fields.Item("AutoKey").Value.ToString());

            #region 获取父单据的业务类型，以自动生成流水号
            SerialNumber.GetInstance().GetSerialNumberByProc(this.CurrentForm);
            //dbds.SetValue("U_SerialNum", dbds.Offset, CommonEvents.SerialNumber.Trim());

            #endregion

            #region 从委托单复制
            List<string> filter = new List<string>();
            filter.Add("U_SerialNum");
            Dictionary<string, string> mapping = new Dictionary<string, string>();/*Key--业务操作中字段，Value--委托中字段*/
            mapping.Add("U_StartDelegateCode", "U_SPAgencyCode");
            mapping.Add("U_StartDelegateName", "U_SPAgencyName");
            mapping.Add("U_EndDelegateCode", "U_EPAgencyCode");
            mapping.Add("U_EndDelegateName", "U_EPAgencyName");
            mapping.Add("U_FreighterCode", "U_CarrierCode");
            mapping.Add("U_FreighterName", "U_CarrierName");
            //mapping.Add("U_Quantity", "U_Amount");
            mapping.Add("U_StartPortThCode", "U_StartPort");
            mapping.Add("U_StartPort", "U_StartPortEName");
            mapping.Add("U_EndPortThCode", "U_EndPort");
            mapping.Add("U_EndPort", "U_EndPortEName");
            mapping.Add("U_IsClearance", "U_IsClearCustoms");//←进口报关报检的字段名称不同，需要手动匹配
            mapping.Add("U_TransportType", "U_TransportType");//业务单-运输方式 U_TransportType  [modify by WangPeng 2012-4-23]            

            SAPbouiCOM.DBDataSource dbds_OBNO = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);

            Utils.CopyDBDS(SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_DLG1), this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO1), null, null, null, false);

            System.Collections.IEnumerator enumerator = this.CurrentForm.DataSources.DBDataSources.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if ((enumerator.Current as DBDataSource).TableName.EndsWith("BNO6"))
                {
                    Utils.CopyDBDS(fatherForm.DataSources.DBDataSources.Item(AVA_DLG6), this.CurrentForm.DataSources.DBDataSources.Item("@AVA_SE_BNO6"), null, null, null, false);
                    break;
                }
            }

            Utils.CopyDBDS(SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG), dbds_OBNO, null, filter, mapping, true);
            /*客户外文名称*/
            string CardCode = dbds_OBNO.GetValue("U_CardCode", dbds.Offset).Trim();
            rs.DoQuery(string.Format("SELECT CardFName FROM [OCRD] WHERE CardCode=N'{0}' ", CardCode));
            if (rs.RecordCount > 0)
            {
                string foreignName = rs.Fields.Item("CardFName").Value;
                dbds_OBNO.SetValue("U_CardEnglishName", dbds.Offset, foreignName);
            }
            //(this.CurrentForm.Items.Item("mtx_0").Specific as Matrix).LoadFromDataSource();
            DBDataSource dbds_bno3 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3);//主单
            if (dbds_bno3.Size == 0)
            {
                SAPBoAddon.B1Assistant.DBDataSource.AddNewRecordTo(dbds_bno3, 1, "LineId", "VisOrder");
            }
            dbds_bno3.SetValue("U_SenderCode", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_SPAgencyCode", 0));
            dbds_bno3.SetValue("U_Sender", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_SPAgencyName", 0));
            dbds_bno3.SetValue("U_ReceiverCode", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_EPAgencyCode", 0));
            dbds_bno3.SetValue("U_Receiver", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_EPAgencyName", 0));
            if (dbds_bno3.GetValue("U_SenderCode", 0).Trim().Length > 0)
            {
                rs.DoQuery(String.Format("select U_DeliveryContent from OCRD where CardCode = '{0}'", dbds_bno3.GetValue("U_SenderCode", 0)));
                dbds_bno3.SetValue("U_SendDetail", 0, rs.Fields.Item("U_DeliveryContent").Value);
            }
            if (dbds_bno3.GetValue("U_ReceiverCode", 0).Trim().Length > 0)
            {
                rs.DoQuery(String.Format("select U_DeliveryContent from OCRD where CardCode = '{0}'", dbds_bno3.GetValue("U_ReceiverCode", 0)));
                dbds_bno3.SetValue("U_ReceiverDetail", 0, rs.Fields.Item("U_DeliveryContent").Value);
            }
            DBDataSource dbds_bno4 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4);//分单
            if (dbds_bno4.Size == 0)//如果没有行，自动创建一行
            {
                SAPBoAddon.B1Assistant.DBDataSource.AddNewRecordTo(dbds_bno4, 1, "LineId", "VisOrder");
            }
            dbds_bno4.SetValue("U_SenderCode", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_ShipperCode", 0));
            dbds_bno4.SetValue("U_Sender", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_ShipperInfo", 0));
            dbds_bno4.SetValue("U_SendDetail", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_ShipperDetInfo", 0));
            dbds_bno4.SetValue("U_ReceiverCode", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_consigneeCode", 0));
            dbds_bno4.SetValue("U_Receiver", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_consigneeInfo", 0));
            dbds_bno4.SetValue("U_ReceiverDetail", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_ConsigneeDetInfo", 0));
            dbds_bno4.SetValue("U_NotifierCode", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_NotifyCode", 0));
            dbds_bno4.SetValue("U_Notifier", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_NotifyParty", 0));
            dbds_bno4.SetValue("U_NotificationDatail", 0, SBOApp.Forms.Item(odlg_formuid).DataSources.DBDataSources.Item(AVA_ODLG).GetValue("U_NotifyPartyInfo", 0));

            #endregion

            Utils.InitialCargoComboBox(this.SBOCompany, this.CurrentForm, Cargo_UID_Field);

            this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_DocDate", 0, DateTime.Now.ToString("yyyyMMdd"));
            this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_BaseType", 0, fatherForm.TypeEx.Trim());
            this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_BaseEntry", 0, odlg_entry);
            this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_BaseSerial", 0, BaseSerial);
        }
        /// <summary>
        /// 多个委托单生成一个业务单
        /// </summary>
        /// <param name="fatherFormUID"></param>
        private void CreateNewFromDelegateList(string fatherFormUID)
        {
            Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string onnm = String.Format("select AutoKey from ONNM WITH(UPDLOCK) where ObjectCode = '{0}'", this.CurrentForm.TypeEx);
            rs.DoQuery(onnm);
            this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("DocEntry", 0, rs.Fields.Item("AutoKey").Value.ToString());

            Form fatherForm = SBOApp.Forms.Item(fatherFormUID);
            SAPbouiCOM.UserDataSource BaseEntry = fatherForm.DataSources.UserDataSources.Item("BaseEntry");
            SAPbouiCOM.Grid grid = fatherForm.Items.Item("Grid").Specific;
            List<string> BaseEntries = new List<string>();
            List<string> BaseSerials = new List<string>();
            for (int i = 0; i < grid.DataTable.Rows.Count; i++)
            {
                object obj = grid.DataTable.Columns.Item(0).Cells.Item(i).Value;
                if (obj.ToString() == "Y")//checkBox选中后就返回Y
                {
                    BaseEntries.Add(grid.DataTable.Columns.Item(1).Cells.Item(i).Value.ToString().Trim());
                    BaseSerials.Add(grid.DataTable.Columns.Item(2).Cells.Item(i).Value.ToString().Trim());
                }
            }
            if (BaseEntries.Count > 0)
            {
                try
                {
                    #region 数据初始化
                    DBDataSource dbds_obno = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                    DBDataSource dbds_bno1 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO1);
                    DBDataSource dbds_bno2 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO2);
                    DBDataSource dbds_bno3 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO3);
                    DBDataSource dbds_bno4 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO4);
                    DBDataSource dbds_bno5 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_BNO5);
                    DBDataSource dbds_odlg = this.CurrentForm.DataSources.DBDataSources.Item(AVA_ODLG);
                    DBDataSource dbds_dlg1 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_DLG1);
                    DBDataSource dbds_dlg2 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_DLG2);
                    DBDataSource dbds_dlg3 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_DLG3);

                    DBDataSource dbds_bno6 = null;
                    DBDataSource dbds_dlg5 = null;
                    System.Collections.IEnumerator enumerator = this.CurrentForm.DataSources.DBDataSources.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        if ((enumerator.Current as DBDataSource).TableName.EndsWith("BNO6"))
                        {
                            dbds_bno6 = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_SE_BNO6");
                            dbds_dlg5 = this.CurrentForm.DataSources.DBDataSources.Item("@AVA_SE_DLG5");
                        }
                    }


                    SAPbouiCOM.Conditions conditions = new Conditions();
                    SAPbouiCOM.Condition condition = conditions.Add();
                    condition.Alias = "DocEntry";
                    condition.CondVal = BaseEntries[0];
                    condition.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                    dbds_odlg.Query(conditions);
                    condition.Relationship = BoConditionRelationship.cr_OR;
                    for (int i = 1; i < BaseEntries.Count; i++)
                    {
                        condition = conditions.Add();
                        condition.Alias = "DocEntry";
                        condition.CondVal = BaseEntries[i];
                        condition.Operation = SAPbouiCOM.BoConditionOperation.co_EQUAL;
                        condition.Relationship = BoConditionRelationship.cr_OR;
                    }
                    condition.Relationship = BoConditionRelationship.cr_NONE;

                    //dbds_odlg.Query(conditions);
                    dbds_dlg1.Query(conditions);
                    dbds_dlg2.Query(conditions);
                    dbds_dlg3.Query(conditions);
                    if (dbds_dlg5 != null)
                    {
                        dbds_dlg5.Query(conditions);
                    }

                    string select_onnm = String.Format("select AutoKey from ONNM WITH(UPDLOCK) where ObjectCode = 'AVA_" + BusinessType + "_BusinessOpera'");
                    rs.DoQuery(select_onnm);
                    int thisEntry = Convert.ToInt32(rs.Fields.Item("AutoKey").Value);//AutoKey在ONNM已经+1
                    #endregion
                    Dictionary<string, Object> odlg_initial = new Dictionary<string, Object>();
                    odlg_initial.Add("DocEntry", thisEntry);
                    odlg_initial.Add("U_BaseEntry", String.Join(",", BaseEntries));

                    List<string> filter = new List<string>();
                    filter.Add("U_SerialNum");
                    filter.Add("U_Status");//←根据需要扩展，还有DocDate等，都没必要复制
                    Dictionary<string, string> mapping = new Dictionary<string, string>();/*Key--业务操作中字段，Value--委托中字段*/
                    mapping.Add("U_StartDelegateCode", "U_SPAgencyCode");
                    mapping.Add("U_StartDelegateName", "U_SPAgencyName");
                    mapping.Add("U_EndDelegateCode", "U_EPAgencyCode");
                    mapping.Add("U_EndDelegateName", "U_EPAgencyName");
                    mapping.Add("U_FreighterCode", "U_CarrierCode");
                    mapping.Add("U_FreighterName", "U_CarrierName");
                    mapping.Add("U_StartPortThCode", "U_StartPort");
                    mapping.Add("U_StartPort", "U_StartPortEName");
                    mapping.Add("U_EndPortThCode", "U_EndPort");
                    mapping.Add("U_EndPort", "U_EndPortEName");
                    mapping.Add("U_IsClearance", "U_IsClearCustoms");//←进口报关报检的字段名称不同，需要手动匹配
                    mapping.Add("U_TransportType", "U_TransportType");//业务单-运输方式 U_TransportType  [modify by WangPeng 2012-4-23]
                    mapping.Add("U_ETA", "U_ReserveStartDate");
                    mapping.Add("U_ETD", "U_PSDate");

                    #region 海运业务单特有字段
                    if (fatherForm.DataSources.UserDataSources.Item("fatherUID").Value.StartsWith("AVA_SE_Delegate"))
                    {
                        mapping.Add("U_Bargain", "U_Bargain");
                    }
                    #endregion
                    Utils.CopyDBDS(dbds_dlg1, dbds_bno1, null, null, null, false);

                    for (int i = dbds_bno1.Size - 1; i >= 0; i--)//如果品名和英文品名都为空，则删除该条数据
                    {
                        if (dbds_bno1.GetValue("U_CargoName", i).Trim() == "" && dbds_bno1.GetValue("U_CargoEName", i).Trim() == "")
                        {
                            dbds_bno1.RemoveRecord(i);
                        }
                    }
                    if (dbds_dlg5 != null)
                    {
                        Utils.CopyDBDS(dbds_dlg5, dbds_bno6, null, null, null, false);
                    }
                    Utils.CopyDBDS(dbds_odlg, dbds_obno, null, filter, mapping, true);
                    /*取当前用户赋值给操纵者 added by WangPeng 2012-6-19*/
                    dynamic Operator = Utils.GetCurrentUser();
                    dbds_obno.SetValue("U_Operator", dbds_obno.Offset, Operator.Operator);
                    dbds_obno.SetValue("U_OperatorCode", dbds_obno.Offset, Operator.empID);
                    /*取当前用户的客服 added by WangPeng 2012-6-13*/
                    Int32 empID = Convert.ToInt32(Utils.GetCurrentUser().empID);
                    this.GetServiceName();//   dbds_obno.SetValue("U_ServiceName", dbds_obno.Offset, Utils.GetClientService(empID))

                    /*客户外文名称*/
                    string CardCode = dbds_obno.GetValue("U_CardCode", dbds_obno.Offset).Trim();
                    rs.DoQuery(string.Format("SELECT CardFName FROM [OCRD] WHERE CardCode=N'{0}' ", CardCode));
                    if (rs.RecordCount > 0)
                    {
                        string foreignName = rs.Fields.Item("CardFName").Value;
                        dbds_obno.SetValue("U_CardEnglishName", dbds_obno.Offset, foreignName);
                    }
                    //dbds_bno3主单
                    if (dbds_bno3.Size == 0)
                    {
                        SAPBoAddon.B1Assistant.DBDataSource.AddNewRecordTo(dbds_bno3, 1, "LineId", "VisOrder");
                    }
                    dbds_bno3.SetValue("U_SenderCode", 0, dbds_odlg.GetValue("U_SPAgencyCode", 0));
                    dbds_bno3.SetValue("U_Sender", 0, dbds_odlg.GetValue("U_SPAgencyName", 0));
                    dbds_bno3.SetValue("U_ReceiverCode", 0, dbds_odlg.GetValue("U_EPAgencyCode", 0));
                    dbds_bno3.SetValue("U_Receiver", 0, dbds_odlg.GetValue("U_EPAgencyName", 0));
                    if (dbds_bno3.GetValue("U_SenderCode", 0).Trim().Length > 0)
                    {
                        rs.DoQuery(String.Format("select U_DeliveryContent from OCRD where CardCode = '{0}'", dbds_bno3.GetValue("U_SenderCode", 0)));
                        dbds_bno3.SetValue("U_SendDetail", 0, rs.Fields.Item("U_DeliveryContent").Value);
                    }
                    if (dbds_bno3.GetValue("U_ReceiverCode", 0).Trim().Length > 0)
                    {
                        rs.DoQuery(String.Format("select U_DeliveryContent from OCRD where CardCode = '{0}'", dbds_bno3.GetValue("U_ReceiverCode", 0)));
                        dbds_bno3.SetValue("U_ReceiverDetail", 0, rs.Fields.Item("U_DeliveryContent").Value);
                    }
                    //dbds_bno4分单
                    if (dbds_bno4.Size == 0)//如果没有行，自动创建一行
                    {
                        SAPBoAddon.B1Assistant.DBDataSource.AddNewRecordTo(dbds_bno4, 1, "LineId", "VisOrder");
                    }
                    dbds_bno4.SetValue("U_SenderCode", 0, dbds_odlg.GetValue("U_ShipperCode", 0));
                    dbds_bno4.SetValue("U_Sender", 0, dbds_odlg.GetValue("U_ShipperInfo", 0));
                    dbds_bno4.SetValue("U_SendDetail", 0, dbds_odlg.GetValue("U_ShipperDetInfo", 0));
                    dbds_bno4.SetValue("U_ReceiverCode", 0, dbds_odlg.GetValue("U_consigneeCode", 0));
                    dbds_bno4.SetValue("U_Receiver", 0, dbds_odlg.GetValue("U_consigneeInfo", 0));
                    dbds_bno4.SetValue("U_ReceiverDetail", 0, dbds_odlg.GetValue("U_ConsigneeDetInfo", 0));
                    dbds_bno4.SetValue("U_NotifierCode", 0, dbds_odlg.GetValue("U_NotifyCode", 0));
                    dbds_bno4.SetValue("U_Notifier", 0, dbds_odlg.GetValue("U_NotifyParty", 0));
                    dbds_bno4.SetValue("U_NotificationDatail", 0, dbds_odlg.GetValue("U_NotifyPartyInfo", 0));

                    Utils.InitialCargoComboBox(this.SBOCompany, this.CurrentForm, Cargo_UID_Field);

                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_DocDate", 0, DateTime.Now.ToString("yyyyMMdd"));
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_BaseType", 0, SourceObject);
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_BaseEntry", 0, String.Join(",", BaseEntries));//数字型，不能存多个
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue("U_BaseSerial", 0, String.Join(",", BaseSerials));
                    SerialNumber.GetInstance().RecoveryTransportType = dbds_obno.GetValue("U_TransportType", dbds_obno.Offset).Trim();
                    SerialNumber.GetInstance().GetSerialNumberByProc(this.CurrentForm);/*流水号赋值*/
                    //基于上游单据生成时，新单据总是所有控件均可以编辑，所以强制加上了这句话（by Webb.Wen at 2012-04-12 13:57:13）
                    SAPBoAddon.B1Assistant.Item.SetEnabled(this.CurrentForm, FormSetting.FormModeSetting.itmNewModeDisable, false);
                }
                catch (Exception ex)
                {
                    SBOApp.StatusBar.SetText(String.Format("{0},委托单创建失败！", ex.Message), SAPbouiCOM.BoMessageTime.bmt_Medium, SAPbouiCOM.BoStatusBarMessageType.smt_Error);
                }
                finally
                {

                }
            }
        }
        /// <summary>
        /// 更新所有来源委托单的状态为“已结算”
        /// </summary>
        private void UpdateSourceOrderStatus()
        {
            DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
            string docEntry = dbds.GetValue("DocEntry", 0).Trim();
            if (string.IsNullOrWhiteSpace(dbds.GetValue("U_BaseType", 0).Trim())) return;
            if (dbds.GetValue("U_BaseType", 0).Trim() == "AVA_" + BusinessType + "_Delegate")
            {
                Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                foreach (var item in dbds.GetValue("U_BaseEntry", 0).Trim().Split(','))
                {
                    if (CurrentForm.Mode == BoFormMode.fm_ADD_MODE)
                    {
                        //更新委托单的状态
                        rs.DoQuery(String.Format(@"UPDATE T1 SET T1.U_Status = 'C',T1.U_TargetEntry = {0}  FROM [" + AVA_ODLG + "] T1 Where T1.DocEntry = '{1}'", docEntry, item));
                    }
                    rs.DoQuery("SELECT U_BaseEntry FROM [" + AVA_ODLG + "] Where DocEntry = '" + item + "'");
                    string Orders = rs.Fields.Item("U_BaseEntry").Value.ToString();
                    foreach (string Order in Orders.Trim().Split(','))
                    {
                        //更新订单的状态
                        rs.DoQuery(String.Format(@"UPDATE T2 SET T2.U_Status = Case When T0.U_Status = 'P' Then 'R' When T0.U_Status = 'R' Then 'C' End  FROM [" + AVA_OBNO + "] T0 INNER JOIN [" + AVA_ODLG + "] T1 ON T1.DocEntry = '{1}'  INNER JOIN [@AVA_" + BusinessType + "_OSOD] T2 ON T2.DocEntry = '{2}' Where T0.U_BaseType = 'AVA_" + BusinessType + "_Delegate' And T0.DocEntry = '{0}'", docEntry, item, Order));
                    }
                }
            }
            //到港
            if (dbds.GetValue("U_BaseType", 0).Trim() == "AVA_" + BusinessType + "_ArrivePort")
            {
                Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                if (CurrentForm.Mode == BoFormMode.fm_ADD_MODE)
                {
                    string SQL = String.Format(@"UPDATE T1 
                                                SET T1.U_TargetSerial = '{1}'
                                                    ,T1.U_TargetEntry = '{2}'
                                                    ,T1.U_TargetMBLNum = '{3}'  
                                                FROM [@AVA_" + BusinessType + "_OARP] T1 Where T1.DocEntry = '{0}'"
                                            , dbds.GetValue("U_BaseEntry", 0).Trim()
                                            , dbds.GetValue("U_SerialNum", 0).Trim()
                                            , dbds.GetValue("DocEntry", 0).Trim()
                                            , dbds.GetValue("U_MBLNumber", 0).Trim());
                    //到港信息
                    rs.DoQuery(SQL);
                }
            }
            //空运业务单
            if (dbds.GetValue("U_BaseType", 0).Trim() == "AVA_" + BusinessType + "_BusinessOpera")
            {
                Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                if (CurrentForm.Mode == BoFormMode.fm_ADD_MODE)
                {
                    string SQL = String.Format(@"UPDATE T1 
                                                SET T1.U_TargetSerial = '{1}'
                                                    ,T1.U_TargetEntry = '{2}'
                                                    ,T1.U_TargetMBLNum = '{3}'  
                                                    ,T1.U_TargetSBLNum = '{4}'
                                                FROM [@AVA_FF_OBNO] T1 Where T1.DocEntry = '{0}'"
                                            , dbds.GetValue("U_BaseEntry", 0).Trim()
                                            , dbds.GetValue("U_SerialNum", 0).Trim()
                                            , dbds.GetValue("DocEntry", 0).Trim()
                                            , dbds.GetValue("U_MBLNumber", 0).Trim()
                                            , dbds.GetValue("U_SBLNumber", 0).Trim());
                    //到港信息
                    rs.DoQuery(SQL);
                }
            }
        }
        /// <summary>
        /// 检查费用单据是否存在
        /// </summary>
        /// <param name="BubbleEvent"></param>
        private void CheckChargeOrderExist(ref bool BubbleEvent)
        {
            if (SAPBoAddon.B1Assistant.Item.GetValue(CurrentForm, "7").ToString().Trim() != "D")
                return;

            SAPbouiCOM.DBDataSource dbds = CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
            string DocEntry = dbds.GetValue("DocEntry", dbds.Offset).Trim();
            string BusType = string.Empty;
            switch (CurrentForm.TypeEx)
            {
                case B1FormTypes.ado_AVA_FF_BusinessOperation:
                    BusType = "A";
                    break;
                case B1FormTypes.ado_AVA_SE_BusinessOperation:
                    BusType = "S";
                    break;
                case B1FormTypes.ado_AVA_LN_BusinessOperation:
                    BusType = "L";
                    break;
                case B1FormTypes.ado_AVA_OR_BusinessOperation:
                    BusType = "O";
                    break;
            }
            SAPbobsCOM.Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string SQL = @"
                            SELECT SUM([Counter])
                            FROM (
	                            SELECT COUNT('A') [Counter]
		                        FROM ORDR T0
			                        INNER JOIN RDR1 T1 ON T0.DocEntry = T1.DocEntry 
			                        LEFT JOIN [DLN1] T3 ON T1.DocEntry=ISNULL(T3.BaseEntry,-1) AND T1.LineNum=ISNULL(T3.BaseLine,-1)
			                        LEFT JOIN [INV1] T4 ON T3.DocEntry=ISNULL(T4.BaseEntry,-1) AND T3.LineNum=ISNULL(T4.BaseLine,-1) AND T4.BaseType=15
			                        LEFT JOIN [INV1] T5 ON T1.DocEntry=ISNULL(T5.BaseEntry,-1) AND T1.LineNum=ISNULL(T5.BaseLine,-1) AND T5.BaseType=17
		                        Where T0.CANCELED = 'N'  AND ISNULL(T0.U_BoType,N'')='{0}'  And T0.U_BoEntry = '{1}' 
		                         AND T1.LinManClsd<>N'Y' --非手动关闭行
		                         AND ISNULL(T3.TargetType,-1)<>16  --销售订单交货目标凭证不是[退货]
		                         AND ISNULL(T4.TargetType,-1)<>14  --应收发票目标凭证不是[贷项凭证]
		                         AND ISNULL(T5.TargetType,-1)<>14  --应收发票目标凭证不是[贷项凭证]

	                            UNION ALL	

	                            SELECT COUNT('A') Counter
		                        FROM OPOR T0
			                        INNER JOIN POR1 T1 ON T0.DocEntry = T1.DocEntry 			                        
			                        LEFT JOIN [PDN1] T3 ON T1.DocEntry=ISNULL(T3.BaseEntry,-1) AND T1.LineNum=ISNULL(T3.BaseLine,-1)
			                        LEFT JOIN [PCH1] T4 ON T3.DocEntry=ISNULL(T4.BaseEntry,-1) AND T3.LineNum=ISNULL(T4.BaseLine,-1)  AND T4.BaseType=20
			                        LEFT JOIN [PCH1] T5 ON T1.DocEntry=ISNULL(T5.BaseEntry,-1) AND T1.LineNum=ISNULL(T5.BaseLine,-1)  AND T5.BaseType=22
		                        Where T0.CANCELED = 'N'  AND ISNULL(T0.U_BoType,N'')='{0}' And T0.U_BoEntry = '{1}' 
		                         AND T1.LinManClsd<>N'Y' --非手动关闭行
		                         AND ISNULL(T3.TargetType,-1)<>21  --采购订单收货目标凭证不是[退货]
		                         AND ISNULL(T4.TargetType,-1)<>19  --应付发票目标凭证不是[贷项凭证]
		                         AND ISNULL(T5.TargetType,-1)<>19  --应付发票目标凭证不是[贷项凭证]
                            ) T0                            ";
            SQL = string.Format(SQL, BusType, DocEntry);
            rs.DoQuery(SQL);
            if (rs.Fields.Item(0).Value > 0)
            {
                SBOApp.MessageBox("此业务单有费用没有取消不能直接作废，需要处理费用。\r\n需要先把费用取消，再进行作废操作。\r\n\r\n操作方法：\r\n1、打开制作费用。\r\n2、删除费用项。");
                BubbleEvent = false;
                return;
            }
        }
        /// <summary>
        /// 从到港复制
        /// </summary>
        /// <param name="ParentFormUID"></param>
        private void CopyFromArrivePort(string ParentFormUID)
        {
            Form oForm;
            Form oParentForm;
            DBDataSource oParentdbds = null;
            DBDataSource dbds;
            string BaseEntry = string.Empty;
            string BaseSerial = string.Empty;
            try
            {
                oForm = CurrentForm;
                //oForm.Mode = BoFormMode.fm_ADD_MODE;
                Utils.SetRemarkByItem(this.CurrentForm, "13", "ABC");
                SBOApp.Menus.Item(B1MenuTypes.sys_Add).Activate();

                dbds = oForm.DataSources.DBDataSources.Item(AVA_OBNO);

                oParentForm = SBOApp.Forms.Item(ParentFormUID);

                IEnumerator dbdsEnumerator = oParentForm.DataSources.DBDataSources.GetEnumerator();
                while (dbdsEnumerator.MoveNext())
                {
                    DBDataSource d = dbdsEnumerator.Current as DBDataSource;
                    if (!new System.Text.RegularExpressions.Regex(@"\d+\b").Match(d.TableName).Success)
                    {

                        oParentdbds = d;
                    }
                }
                BaseEntry = oParentdbds.GetValue("DocEntry", oParentdbds.Offset).Trim();
                BaseSerial = oParentdbds.GetValue("U_SerialNum", oParentdbds.Offset).Trim();

                oForm.DataSources.UserDataSources.Item("BaseEntry").Value = BaseEntry;//指向父窗体
                oForm.DataSources.UserDataSources.Item("ParentUID").Value = ParentFormUID;//指向父窗体

                Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                string onnm = String.Format("select AutoKey from ONNM WITH(UPDLOCK) where ObjectCode = '{0}'", oForm.TypeEx.Trim());
                rs.DoQuery(onnm);
                dbds.SetValue("DocEntry", 0, rs.Fields.Item("AutoKey").Value.ToString());
                dbds.SetValue("U_TransportType", dbds.Offset, oParentdbds.GetValue("U_OnwardTransMode", oParentdbds.Offset).Trim());//运输方式
                SerialNumber.GetInstance().GetSerialNumberByProc(oForm);
                //dbds.SetValue("U_SerialNum", dbds.Offset, CommonEvents.SerialNumber.Trim());

                Utils.InitialCargoComboBox(this.SBOCompany, oForm, Cargo_UID_Field);

                dbds.SetValue("U_DocDate", 0, DateTime.Now.ToString("yyyyMMdd"));
                dbds.SetValue("U_BaseType", 0, oParentForm.TypeEx.Trim());
                dbds.SetValue("U_BaseEntry", 0, BaseEntry);
                dbds.SetValue("U_BaseSerial", 0, BaseSerial);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 续程复制
        /// </summary>
        /// <param name="ParentFormUID"></param>
        private void CopyFromOperaGoOnPort(string ParentFormUID)
        {
            Form oForm;
            Form oParentForm;
            DBDataSource oParentdbds = null;
            DBDataSource dbds;
            string BaseEntry = string.Empty;
            string BaseSerial = string.Empty;
            try
            {
                oForm = CurrentForm;
                //oForm.Mode = BoFormMode.fm_ADD_MODE;
                Utils.SetRemarkByItem(this.CurrentForm, "13", "ABC");
                SBOApp.Menus.Item(B1MenuTypes.sys_Add).Activate();

                dbds = oForm.DataSources.DBDataSources.Item(AVA_OBNO);

                oParentForm = SBOApp.Forms.Item(ParentFormUID);

                oParentdbds = oParentForm.DataSources.DBDataSources.Item("@AVA_FF_OBNO");
                BaseEntry = oParentdbds.GetValue("DocEntry", oParentdbds.Offset).Trim();
                BaseSerial = oParentdbds.GetValue("U_SerialNum", oParentdbds.Offset).Trim();

                oForm.DataSources.UserDataSources.Item("BaseEntry").Value = BaseEntry;//指向父窗体
                oForm.DataSources.UserDataSources.Item("ParentUID").Value = ParentFormUID;//指向父窗体

                Recordset rs = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                string onnm = String.Format("select AutoKey from ONNM WITH(UPDLOCK) where ObjectCode = '{0}'", oForm.TypeEx.Trim());
                rs.DoQuery(onnm);
                dbds.SetValue("DocEntry", 0, rs.Fields.Item("AutoKey").Value.ToString());
                dbds.SetValue("U_TransportType", dbds.Offset, oParentdbds.GetValue("U_OnwardTransMode", oParentdbds.Offset).Trim());//运输方式
                SerialNumber.GetInstance().GetSerialNumberByProc(oForm);
                //dbds.SetValue("U_SerialNum", dbds.Offset, CommonEvents.SerialNumber.Trim());

                Utils.InitialCargoComboBox(this.SBOCompany, oForm, Cargo_UID_Field);

                dbds.SetValue("U_DocDate", 0, DateTime.Now.ToString("yyyyMMdd"));
                dbds.SetValue("U_BaseType", 0, oParentForm.TypeEx.Trim());
                dbds.SetValue("U_BaseEntry", 0, BaseEntry);
                dbds.SetValue("U_BaseSerial", 0, BaseSerial);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #region 子单据的处理
        /*
         * 效果：
         * 主窗体CheckBox勾选时，不显示任何效果，双击时才弹出列表（此时的确不触发事件）
         * 双击可以显示具体列表窗体（UserDataSource存在，打开，不存在，创建并打开，并写入UserDataSource，还是Lazy Initialize的模式）
         * 在添加模式下，不管是列表窗体还是列表窗体中对应的子对象窗体，点击“确认”只是触发隐藏操作
         * 在更新模式下，列表窗体点击“确认”还是触发隐藏操作，子对象窗体直接触发UI的更新
         * 列表中可以添加一个新的子对象，也可以删除一个旧子对象，此时直接根据DocEntry入库删除
         * 保存时，遍历子对象列表窗体的子对象窗体，RecordSet添加。如果子对象窗体没有对象，对应的字段置为N
        */
        /// <summary>
        /// 关闭当前窗体，释放资源（因为很多子窗体和列表窗体都是隐藏显示的）
        /// 由于当前窗体的保存独立于子窗体的保存，所以无法放到一个事物中
        /// 有可能出现的情况是，子窗体的保存已经完成，但是在保存当前主窗体表单的时候发生异常保存失败
        /// 这时可能出现的情况是，数据库中已经存在子对象，但是主对象却没有
        /// 所以在关闭当前窗体的时候，做个处理
        /// </summary>
        private List<string> CloseSonForms(bool close = true)
        {
            List<string> sonFormUids = new List<string>();
            foreach (Form listForm in SBOApp.Forms)
            {
                //if (form.IsSystem) continue;
                foreach (string item in CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC)
                {
                    string sonFormUid = item.Split(':')[2];
                    if (listForm.UniqueID == this.CurrentForm.DataSources.UserDataSources.Item(sonFormUid).Value)
                    {
                        DataTable table = listForm.DataSources.DataTables.Item("DT");
                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            string formUid = table.GetValue("FormUID", i).ToString();
                            if (!String.IsNullOrEmpty(formUid))
                            {
                                foreach (Form sonForm in SBOApp.Forms)
                                {
                                    if (sonForm.UniqueID == formUid)
                                    {
                                        sonFormUids.Add(sonForm.UniqueID);
                                        //sonForm.Visible = true;
                                        sonForm.Mode = BoFormMode.fm_OK_MODE;
                                        if (close)
                                        {
                                            //sonForm.Close();
                                            sonForm.Items.Item("2").Visible = true;
                                            sonForm.Items.Item("2").Click(BoCellClickType.ct_Regular);
                                        }
                                        break;

                                    }
                                }
                            }
                        }
                        if (close)
                            listForm.Close();//关闭所有子窗体，至少释放资源
                    }
                }
            }
            return sonFormUids;
        }
        /// <summary>
        /// 清空UserDataSource中保存的子窗体uid
        /// </summary>
        private void ClearUserDateSource()
        {
            if (this.CurrentForm != null)
            {
                foreach (var item in CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC)
                {
                    string sonFormUid = item.Split(':')[2];
                    this.CurrentForm.DataSources.UserDataSources.Item(sonFormUid).Value = "";
                }
            }
        }
        /// <summary>
        /// CheckBox选中项变更事件
        /// </summary>
        /// <param name="pVal"></param>
        /// <param name="BubbleEvent"></param>
        private void ClickSonCheckBox(SAPBoAddon.B1AddonBase.B1ItemEvent pVal, ref bool BubbleEvent)
        {
            SAPbouiCOM.Form listForm = null;
            CheckBox cb = this.CurrentForm.Items.Item(pVal.ItemUID).Specific;//即使是Before，cb.Checked也是在事件之前
            string sonFormUserDataSourceUid = String.Empty;
            string sonFormSrf = String.Empty;
            string sonTable = String.Empty;
            string sonObjectType = String.Empty;
            string thisDocEntry = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).GetValue("DocEntry", 0).Trim();
            string dbdsField = String.Empty;
            string config = CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Contains(String.Format("{0}:", pVal.ItemUID)));
            if (String.IsNullOrEmpty(config))
            {
                return;
            }
            sonFormUserDataSourceUid = config.Split(':')[2];
            dbdsField = CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Contains(String.Format(":{0}:", sonFormUserDataSourceUid))).Split(':')[3];
            sonObjectType = CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Contains(String.Format(":{0}:", sonFormUserDataSourceUid))).Split(':')[4];
            sonTable = CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Contains(String.Format(":{0}:", sonFormUserDataSourceUid))).Split(':')[5].Split('/')[0];
            if (cb.Checked == true)//如果要勾选为选中，则DBDS对应值已经改变，不需要做处理
            {

            }
            else//如果要勾选为不选中，清理资源，包括UserDataSource，关闭对应子窗体
            {
                //是做到添加状态下即时清理资源，更新状态下最后保存时再确认是否删除
                //还是统一到保存的时候确认是否删除，并清理资源？
                int dialogResult = SBOApp.MessageBox("取消后已经保存的子单据将会丢失，是否继续？", 2, "确定", "取消");
                if (dialogResult == 1)
                {
                    if (this.CurrentForm.DataSources.UserDataSources.Item(sonFormUserDataSourceUid).Value.Length > 0)
                    {
                        listForm = SBOApp.Forms.Item(this.CurrentForm.DataSources.UserDataSources.Item(sonFormUserDataSourceUid).Value);

                        Grid grid = listForm.Items.Item("Grid").Specific as Grid;
                        for (int i = 0; i < grid.DataTable.Rows.Count; i++)
                        {
                            string formUid = grid.DataTable.GetValue("FormUID", i).ToString().Trim();
                            if (!String.IsNullOrEmpty(formUid))
                            {
                                Form sonForm = Utils.GetForm(this.SBOApp, formUid);// this.SBOApp.Forms.Item(formUid);
                                if (sonForm != null)
                                {
                                    sonForm.Items.Item("2").Visible = true;
                                    sonForm.Items.Item("2").Click(BoCellClickType.ct_Regular);
                                }
                                //sonForm.Close();
                            }
                        }

                        listForm.Close();
                        this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue(dbdsField, 0, "N");
                        this.CurrentForm.DataSources.UserDataSources.Item(sonFormUserDataSourceUid).Value = "";
                    }
                }
                else
                {
                    this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).SetValue(dbdsField, 0, "Y");
                    BubbleEvent = false;
                }

            }
        }
        /// <summary>
        /// Label点击事件
        /// </summary>
        /// <param name="pVal"></param>
        private void ClickSonLabel(SAPBoAddon.B1AddonBase.B1ItemEvent pVal)
        {
            string sonTable = String.Empty;
            string sonObjectType = String.Empty;
            string dbdsField = String.Empty;
            string BNOEntry = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).GetValue("DocEntry", 0);
            string config = CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Contains(String.Format(":{0}:", pVal.ItemUID)));
            if (String.IsNullOrEmpty(config))
            {
                return;
            }
            string sonFormUserDataSourceUid = config.Split(':')[2];

            dbdsField = CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Contains(String.Format(":{0}:", sonFormUserDataSourceUid))).Split(':')[3];

            if (this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO).GetValue(dbdsField, 0) == "Y")
            {
                sonObjectType = config.Split(':')[4];
                sonTable = config.Split(':')[5].Split('/')[0];

                //看UserDataSource是否存在，存在直接打开
                //否则创建
                if (this.CurrentForm.DataSources.UserDataSources.Item(sonFormUserDataSourceUid).Value.Length > 0)
                {
                    Form listForm = this.SBOApp.Forms.Item(this.CurrentForm.DataSources.UserDataSources.Item(sonFormUserDataSourceUid).Value);
                    Grid grid = listForm.Items.Item("Grid").Specific;
                    if (grid.DataTable.Rows.Count > 0 && grid.DataTable.GetValue("DocEntry", 0).ToString() == "0")//默认有一个空行，DocEntry=0
                    {
                        grid.DataTable.Rows.Remove(0);
                    }
                    //隐藏列表窗体，直接展现子对象窗体（如果不存在，创建一个子对象窗体并展现）
                    if (grid.DataTable.Rows.Count == 0)
                    {
                        listForm.Visible = false;
                        Utils.AddSonForm(SBOApp, listForm.UniqueID, this.ShowForm);
                        //CreateNewSon(listForm, sonObjectType);
                    }
                    else if (grid.DataTable.Rows.Count <= 1)
                    {
                        listForm.Visible = false;
                        Utils.ShowSonForm(SBOApp, listForm.UniqueID, 0, this.ShowForm);
                        //ShowFirstSon(listForm);
                    }
                    else
                    {
                        listForm.Visible = true;//如果多余两个，还是用列表的形式展现
                    }
                }
                else
                {
                    sonObjectType = CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Contains(String.Format(":{0}:", sonFormUserDataSourceUid))).Split(':')[4];
                    sonTable = CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Contains(String.Format(":{0}:", sonFormUserDataSourceUid))).Split(':')[5].Split('/')[0];
                    InitialSonListForm(sonTable, sonObjectType, sonFormUserDataSourceUid, BNOEntry, false);//创建一个列表窗体，默认设置为隐藏
                    Form listForm = this.SBOApp.Forms.Item(this.CurrentForm.DataSources.UserDataSources.Item(sonFormUserDataSourceUid).Value);
                    Grid grid = listForm.Items.Item("Grid").Specific;
                    if (grid.DataTable.Rows.Count > 0 && grid.DataTable.GetValue("DocEntry", 0).ToString() == "0")//默认有一个空行，DocEntry=0
                    {
                        grid.DataTable.Rows.Remove(0);
                    }
                    if (grid.DataTable.Rows.Count == 0)
                    {
                        //CreateNewSon(listForm, sonObjectType);
                        Utils.AddSonForm(SBOApp, listForm.UniqueID, this.ShowForm);
                    }
                    else if (grid.DataTable.Rows.Count <= 1)
                    {
                        Utils.ShowSonForm(SBOApp, listForm.UniqueID, 0, this.ShowForm);
                        //ShowFirstSon(listForm);
                    }
                    else
                    {
                        listForm.Visible = true;
                    }
                }
            }
        }
        /// <summary>
        /// 初始化列表容器子窗体
        /// </summary>
        /// <param name="sonTable"></param>
        /// <param name="sonType"></param>
        /// <param name="BNOEntry"></param>
        /// <param name="show"></param>
        private void InitialSonListForm(string sonTable, string sonType, string sonFormUserDataSourceUid, string BNOEntry, bool show = false)
        {

            string parms = String.Format("{0};{1};{2};{3};{4}", this.CurrentForm.UniqueID, sonTable, sonType, BNOEntry, sonFormUserDataSourceUid);
            this.ShowForm(B1FormTypes.ado_AVA_FF_BusinessOpreationSonList, parms);
            if (show)
            {
                //string sonFormUserDataSourceUid = CB_LABEL_UDS_DBDS_OBJECT_TABLE_DESC.SingleOrDefault(s => s.Contains(String.Format("{0}", sonTable))).Split(':')[2];
                Form listForm = this.SBOApp.Forms.Item(this.CurrentForm.DataSources.UserDataSources.Item(sonFormUserDataSourceUid).Value);
                listForm.Visible = true;//找到并显示
            }
        }

        /*
         * 2012-05-10 23:56:02修改如下：
         * ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
         * 1.要求主单据保存以后才能保存子单据（更新状态下应该也可以保存，只要主单据存在明确的DocEntry就可以）
         * 2.子单据的保存直接由子单据的UI触发，所以不需要主单据来统一保存
         * 3.子单据通过列表来作为容器，列表窗体本身记录了其容纳的子单据的类型，业务单的编号以及子单据的表名；列表窗体的列表记录了子单据的DocEntry和FormUID，列表窗体的“保存”只是隐藏自己
         * 4.子单据的DocEntry自己控制，每当创建一个子单据的时候，都会去回写列表窗体的DocEntry和FormUID值（如果DocEntry已经存在，则刷新FormUID）
         * 5.双击列表窗体的列的时候，查找对应的FormUID是否存在，如果存在，直接显示，如果不存在，则执行子单据UI的查找，并回写FormUID
         * 6.子单据的更新仍然是触发UI操作
         * 7.由于SAP没有提供明确的API删除子单据对象，所以子单据的删除操作其实是将当前DocEntry的子单据的U_BaseEntry置为NULL
         * 8.回复子单据的"1"和"2"控件，只是"1"一直显示“保存”，而不是“添加/更新”，"2"一直显示取消，不再隐藏
         * 9.业务单窗体可以打开子对象窗体，只需要告诉子窗体：1.业务单编号;2.列表窗体FormUID;3.子对象DocEntry（当该值存在时，执行查找操作，否则执行新建操作）
         * ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
         * 你妹的总算理顺了！
         */

        #endregion
        #region 主单
        /// <summary>
        /// 主单的费用付款方式
        /// </summary>
        /// <param name="FormUID"></param>
        private void MBLChangeCharge(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            decimal WeightCharge;
            oForm = SBOApp.Forms.Item(FormUID);
            oForm.Freeze(true);
            dbds = oForm.DataSources.DBDataSources.Item(AVA_BNO3);
            if (dbds.GetValue("U_FreightPayMethod", dbds.Offset).Trim() == "CC")
            {
                WeightCharge = decimal.Parse(dbds.GetValue("U_PWeightCharge", dbds.Offset));

                dbds.SetValue("U_CWeightCharge", dbds.Offset, WeightCharge.ToString());
                dbds.SetValue("U_PWeightCharge", dbds.Offset, "");
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, "199", false);
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, "270", true);
            }
            else
            {
                WeightCharge = decimal.Parse(dbds.GetValue("U_CWeightCharge", dbds.Offset));

                dbds.SetValue("U_PWeightCharge", dbds.Offset, WeightCharge.ToString());
                dbds.SetValue("U_CWeightCharge", dbds.Offset, "");
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, "199", true);
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, "270", false);
            }
            MBLSum(FormUID);
            oForm.Freeze(false);
        }
        /// <summary>
        /// 主单的其他付款方式
        /// </summary>
        /// <param name="FormUID"></param>
        private void MBLOtherChangeCharge(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            decimal ValuationCharge, Tax, TotalOtherChargeDueAgent, TotalOtherChargeDueCarrer;
            oForm = SBOApp.Forms.Item(FormUID);
            oForm.Freeze(true);
            dbds = oForm.DataSources.DBDataSources.Item(AVA_BNO3);
            if (dbds.GetValue("U_OtherPayMethod", dbds.Offset).Trim() == "CC")
            {

                ValuationCharge = decimal.Parse(dbds.GetValue("U_PValuationCharge", dbds.Offset));
                Tax = decimal.Parse(dbds.GetValue("U_PTax", dbds.Offset));
                TotalOtherChargeDueAgent = decimal.Parse(dbds.GetValue("U_PTOCDA", dbds.Offset));
                TotalOtherChargeDueCarrer = decimal.Parse(dbds.GetValue("U_PTOCDC", dbds.Offset));

                dbds.SetValue("U_CValuationcharge", dbds.Offset, ValuationCharge.ToString());
                dbds.SetValue("U_CTax", dbds.Offset, Tax.ToString());
                dbds.SetValue("U_CTOCDA", dbds.Offset, TotalOtherChargeDueAgent.ToString());
                dbds.SetValue("U_CTOCDC", dbds.Offset, TotalOtherChargeDueCarrer.ToString());

                dbds.SetValue("U_PValuationCharge", dbds.Offset, "");
                dbds.SetValue("U_PTax", dbds.Offset, "");
                dbds.SetValue("U_PTOCDA", dbds.Offset, "");
                dbds.SetValue("U_PTOCDC", dbds.Offset, "");
                dbds.SetValue("U_PTPOTC", dbds.Offset, "");
            }
            else
            {

                ValuationCharge = decimal.Parse(dbds.GetValue("U_CValuationCharge", dbds.Offset));
                Tax = decimal.Parse(dbds.GetValue("U_CTax", dbds.Offset));
                TotalOtherChargeDueAgent = decimal.Parse(dbds.GetValue("U_CTOCDA", dbds.Offset));
                TotalOtherChargeDueCarrer = decimal.Parse(dbds.GetValue("U_CTOCDC", dbds.Offset));

                dbds.SetValue("U_PValuationCharge", dbds.Offset, ValuationCharge.ToString());
                dbds.SetValue("U_PTax", dbds.Offset, Tax.ToString());
                dbds.SetValue("U_PTOCDA", dbds.Offset, TotalOtherChargeDueAgent.ToString());
                dbds.SetValue("U_PTOCDC", dbds.Offset, TotalOtherChargeDueCarrer.ToString());

                dbds.SetValue("U_CValuationCharge", dbds.Offset, "");
                dbds.SetValue("U_CTax", dbds.Offset, "");
                dbds.SetValue("U_CTOCDA", dbds.Offset, "");
                dbds.SetValue("U_CTOCDC", dbds.Offset, "");
                dbds.SetValue("U_CTPOTC", dbds.Offset, "");
            }
            MBLSum(FormUID);
            MBLOtherPayChange(oForm, dbds.GetValue("U_OtherPayMethod", dbds.Offset).Trim());
            oForm.Freeze(false);
        }
        /// <summary>
        /// 燃油、安全、其他费用计算
        /// </summary>
        /// <param name="FormUID"></param>
        private void MBLChargeSum(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;

            decimal TotalOtherChargeDueCarrer, FSC, SSC, OtherCost;

            oForm = SBOApp.Forms.Item(FormUID);
            oForm.Freeze(true);
            dbds = oForm.DataSources.DBDataSources.Item(AVA_BNO3);

            FSC = decimal.Parse(dbds.GetValue("U_FSC", dbds.Offset));
            SSC = decimal.Parse(dbds.GetValue("U_SSC", dbds.Offset));
            OtherCost = decimal.Parse(dbds.GetValue("U_OtherCost", dbds.Offset));
            TotalOtherChargeDueCarrer = FSC + SSC + OtherCost;
            if (dbds.GetValue("U_OtherPayMethod", dbds.Offset).Trim() == "PP")
            {
                dbds.SetValue("U_PTOCDC", dbds.Offset, TotalOtherChargeDueCarrer.ToString());
            }
            else
            {
                dbds.SetValue("U_CTOCDC", dbds.Offset, TotalOtherChargeDueCarrer.ToString());
            }
            //费用合计
            MBLSum(FormUID);
            oForm.Freeze(false);
        }
        /// <summary>
        /// 主单合计的计算
        /// </summary>
        /// <param name="FormUID"></param>
        private void MBLSum(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            decimal WeightCharge, ValuationCharge, Tax, TotalOtherChargeDueAgent, TotalOtherChargeDueCarrer, Total;

            oForm = SBOApp.Forms.Item(FormUID);
            oForm.Freeze(true);
            dbds = oForm.DataSources.DBDataSources.Item(AVA_BNO3);

            WeightCharge = decimal.Parse(dbds.GetValue("U_PWeightCharge", dbds.Offset));
            ValuationCharge = decimal.Parse(dbds.GetValue("U_PValuationCharge", dbds.Offset));
            Tax = decimal.Parse(dbds.GetValue("U_PTax", dbds.Offset));
            TotalOtherChargeDueAgent = decimal.Parse(dbds.GetValue("U_PTOCDA", dbds.Offset));
            TotalOtherChargeDueCarrer = decimal.Parse(dbds.GetValue("U_PTOCDC", dbds.Offset));
            Total = WeightCharge + ValuationCharge + Tax + TotalOtherChargeDueAgent + TotalOtherChargeDueCarrer;

            dbds.SetValue("U_PTPOTC", dbds.Offset, Total.ToString());//PP合计

            WeightCharge = decimal.Parse(dbds.GetValue("U_CWeightCharge", dbds.Offset));
            ValuationCharge = decimal.Parse(dbds.GetValue("U_CValuationCharge", dbds.Offset));
            Tax = decimal.Parse(dbds.GetValue("U_CTax", dbds.Offset));
            TotalOtherChargeDueAgent = decimal.Parse(dbds.GetValue("U_CTOCDA", dbds.Offset));
            TotalOtherChargeDueCarrer = decimal.Parse(dbds.GetValue("U_CTOCDC", dbds.Offset));
            Total = WeightCharge + ValuationCharge + Tax + TotalOtherChargeDueAgent + TotalOtherChargeDueCarrer;

            dbds.SetValue("U_CTPOTC", dbds.Offset, Total.ToString());//CC合计
            oForm.Freeze(false);
        }
        /// <summary>
        /// 主单运费总价
        /// </summary>
        /// <param name="FormUID"></param>
        private void MBLFreightCharge(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            SAPbouiCOM.DBDataSource dbds1;

            Decimal Weight, FreightPrice, Freightsum;

            oForm = SBOApp.Forms.Item(FormUID);
            oForm.Freeze(true);
            dbds = oForm.DataSources.DBDataSources.Item(AVA_OBNO);
            dbds1 = oForm.DataSources.DBDataSources.Item(AVA_BNO3);

            Weight = Decimal.Parse(dbds.GetValue("U_BillingWeight", dbds.Offset).Trim());
            FreightPrice = Decimal.Parse(dbds1.GetValue("U_Price", dbds1.Offset).Trim());
            Freightsum = Weight * FreightPrice;
            dbds1.SetValue("U_TotalPrice", dbds1.Offset, Freightsum.ToString());
            if (dbds1.GetValue("U_FreightPayMethod", dbds1.Offset).Trim() == "PP")
                dbds1.SetValue("U_PWeightCharge", dbds1.Offset, Freightsum.ToString());
            else
                dbds1.SetValue("U_CWeightCharge", dbds1.Offset, Freightsum.ToString());
            MBLSum(FormUID);
            oForm.Freeze(false);
        }
        /// <summary>
        /// 支付方式发生变化时控制的是否可用也随之变化
        /// </summary>
        /// <param name="oForm"></param>
        /// <param name="PayMethod"></param>
        protected void MBLOtherPayChange(SAPbouiCOM.Form oForm, string PayMethod)
        {
            if (CurrentForm.Mode != BoFormMode.fm_ADD_MODE && CurrentForm.Items.Item("7").Enabled == false)
                return;
            string[] PP = new string[] { "195", "197", "203", "205", "1000062" };
            string[] CC = new string[] { "268", "269", "271", "272", "273" };
            if (PayMethod == "CC")
            {
                if (PP.Contains(oForm.ActiveItem))
                {
                    SAPbouiCOM.ComboBox ocmb = oForm.Items.Item("179").Specific;
                    ocmb.Active = true;
                }
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, CC, true);
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, PP, false);
            }
            else
            {
                if (CC.Contains(oForm.ActiveItem))
                {
                    SAPbouiCOM.ComboBox ocmb = oForm.Items.Item("179").Specific;
                    ocmb.Active = true;
                }
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, CC, false);
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, PP, true);
            }
        }
        #endregion
        #region 分单
        /// <summary>
        /// 分单的费用付款方式
        /// </summary>
        /// <param name="FormUID"></param>
        protected void SBLChangeCharge(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            decimal WeightCharge;
            oForm = SBOApp.Forms.Item(FormUID);
            oForm.Freeze(true);
            dbds = oForm.DataSources.DBDataSources.Item(AVA_BNO4);
            if (dbds.GetValue("U_FreightPayMethod", dbds.Offset).Trim() == "CC")
            {
                WeightCharge = decimal.Parse(dbds.GetValue("U_PWeightCharge", dbds.Offset));
                dbds.SetValue("U_CWeightCharge", dbds.Offset, WeightCharge.ToString());
                dbds.SetValue("U_PWeightCharge", dbds.Offset, "");
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, "276", true);
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, "1000105", false);
            }
            else
            {
                WeightCharge = decimal.Parse(dbds.GetValue("U_CWeightCharge", dbds.Offset));
                dbds.SetValue("U_PWeightCharge", dbds.Offset, WeightCharge.ToString());
                dbds.SetValue("U_CWeightCharge", dbds.Offset, "");
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, "276", false);
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, "1000105", true);
            }
            SBLSum(FormUID);
            oForm.Freeze(false);
        }
        /// <summary>
        /// 分单的其他付款方式
        /// </summary>
        /// <param name="FormUID"></param>
        protected void SBLOtherChangeCharge(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            decimal ValuationCharge, Tax, TotalOtherChargeDueAgent, TotalOtherChargeDueCarrer;
            oForm = SBOApp.Forms.Item(FormUID);
            oForm.Freeze(true);
            dbds = oForm.DataSources.DBDataSources.Item(AVA_BNO4);
            if (dbds.GetValue("U_OtherPayMethod", dbds.Offset).Trim() == "CC")
            {
                ValuationCharge = decimal.Parse(dbds.GetValue("U_PValuationCharge", dbds.Offset));
                Tax = decimal.Parse(dbds.GetValue("U_PTax", dbds.Offset));
                TotalOtherChargeDueAgent = decimal.Parse(dbds.GetValue("U_PTOCDA", dbds.Offset));
                TotalOtherChargeDueCarrer = decimal.Parse(dbds.GetValue("U_PTOCDC", dbds.Offset));

                dbds.SetValue("U_CValuationCharge", dbds.Offset, ValuationCharge.ToString());
                dbds.SetValue("U_CTax", dbds.Offset, Tax.ToString());
                dbds.SetValue("U_CTOCDA", dbds.Offset, TotalOtherChargeDueAgent.ToString());
                dbds.SetValue("U_CTOCDC", dbds.Offset, TotalOtherChargeDueCarrer.ToString());

                dbds.SetValue("U_PValuationCharge", dbds.Offset, "");
                dbds.SetValue("U_PTax", dbds.Offset, "");
                dbds.SetValue("U_PTOCDA", dbds.Offset, "");
                dbds.SetValue("U_PTOCDC", dbds.Offset, "");
                dbds.SetValue("U_PTPOTC", dbds.Offset, "");
            }
            else
            {
                ValuationCharge = decimal.Parse(dbds.GetValue("U_CValuationCharge", dbds.Offset));
                Tax = decimal.Parse(dbds.GetValue("U_CTax", dbds.Offset));
                TotalOtherChargeDueAgent = decimal.Parse(dbds.GetValue("U_CTOCDA", dbds.Offset));
                TotalOtherChargeDueCarrer = decimal.Parse(dbds.GetValue("U_CTOCDC", dbds.Offset));

                dbds.SetValue("U_PValuationCharge", dbds.Offset, ValuationCharge.ToString());
                dbds.SetValue("U_PTax", dbds.Offset, Tax.ToString());
                dbds.SetValue("U_PTOCDA", dbds.Offset, TotalOtherChargeDueAgent.ToString());
                dbds.SetValue("U_PTOCDC", dbds.Offset, TotalOtherChargeDueCarrer.ToString());

                dbds.SetValue("U_CValuationCharge", dbds.Offset, "");
                dbds.SetValue("U_CTax", dbds.Offset, "");
                dbds.SetValue("U_CTOCDA", dbds.Offset, "");
                dbds.SetValue("U_CTOCDC", dbds.Offset, "");
                dbds.SetValue("U_CTPOTC", dbds.Offset, "");
            }
            SBLSum(FormUID);
            SBLOtherPayChange(oForm, dbds.GetValue("U_OtherPayMethod", dbds.Offset).Trim());
            oForm.Freeze(false);
        }
        /// <summary>
        /// 分单的燃油、安全、其他费用的合计
        /// </summary>
        /// <param name="FormUID"></param>
        protected void SBLChargeSum(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            decimal TotalOtherChargeDueCarrer, FSC, SSC, OtherCost;
            oForm = SBOApp.Forms.Item(FormUID);
            oForm.Freeze(true);
            dbds = oForm.DataSources.DBDataSources.Item(AVA_BNO4);
            FSC = decimal.Parse(dbds.GetValue("U_FSC", dbds.Offset));
            SSC = decimal.Parse(dbds.GetValue("U_SSC", dbds.Offset));
            OtherCost = decimal.Parse(dbds.GetValue("U_OtherCost", dbds.Offset));
            TotalOtherChargeDueCarrer = FSC + SSC + OtherCost;
            if (dbds.GetValue("U_OtherPayMethod", dbds.Offset).Trim() == "PP")
            {
                dbds.SetValue("U_PTOCDC", dbds.Offset, TotalOtherChargeDueCarrer.ToString());
            }
            else
            {
                dbds.SetValue("U_CTOCDC", dbds.Offset, TotalOtherChargeDueCarrer.ToString());
            }
            SBLSum(FormUID);
            oForm.Freeze(false);
        }
        /// <summary>
        /// 分单合计
        /// </summary>
        /// <param name="FormUID"></param>
        protected void SBLSum(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            decimal WeightCharge, ValuationCharge, Tax, TotalOtherChargeDueAgent, TotalOtherChargeDueCarrer, Total;

            oForm = SBOApp.Forms.Item(FormUID);
            oForm.Freeze(true);
            dbds = oForm.DataSources.DBDataSources.Item(AVA_BNO4);

            WeightCharge = decimal.Parse(dbds.GetValue("U_PWeightCharge", dbds.Offset));
            ValuationCharge = decimal.Parse(dbds.GetValue("U_PValuationCharge", dbds.Offset));
            Tax = decimal.Parse(dbds.GetValue("U_PTax", dbds.Offset));
            TotalOtherChargeDueAgent = decimal.Parse(dbds.GetValue("U_PTOCDA", dbds.Offset));
            TotalOtherChargeDueCarrer = decimal.Parse(dbds.GetValue("U_PTOCDC", dbds.Offset));
            Total = WeightCharge + ValuationCharge + Tax + TotalOtherChargeDueAgent + TotalOtherChargeDueCarrer;

            dbds.SetValue("U_PTPOTC", dbds.Offset, Total.ToString());

            WeightCharge = decimal.Parse(dbds.GetValue("U_CWeightCharge", dbds.Offset));
            ValuationCharge = decimal.Parse(dbds.GetValue("U_CValuationCharge", dbds.Offset));
            Tax = decimal.Parse(dbds.GetValue("U_CTax", dbds.Offset));
            TotalOtherChargeDueAgent = decimal.Parse(dbds.GetValue("U_CTOCDA", dbds.Offset));
            TotalOtherChargeDueCarrer = decimal.Parse(dbds.GetValue("U_CTOCDC", dbds.Offset));
            Total = WeightCharge + ValuationCharge + Tax + TotalOtherChargeDueAgent + TotalOtherChargeDueCarrer;

            dbds.SetValue("U_CTPOTC", dbds.Offset, Total.ToString());
            oForm.Freeze(false);
        }
        /// <summary>
        /// 分单运费
        /// </summary>
        /// <param name="FormUID"></param>
        protected void SBLFreightCharge(string FormUID)
        {
            SAPbouiCOM.Form oForm;
            SAPbouiCOM.DBDataSource dbds;
            SAPbouiCOM.DBDataSource dbds1;

            Decimal Weight, FreightPrice, Freightsum;

            //海运不计算分单运费
            if (BusinessType == "SE")
                return;

            oForm = SBOApp.Forms.Item(FormUID);
            oForm.Freeze(true);
            dbds = oForm.DataSources.DBDataSources.Item(AVA_OBNO);
            dbds1 = oForm.DataSources.DBDataSources.Item(AVA_BNO4);

            Weight = Decimal.Parse(dbds.GetValue("U_BillingWeight", dbds.Offset).Trim());
            FreightPrice = Decimal.Parse(dbds1.GetValue("U_Price", dbds1.Offset).Trim());
            Freightsum = Weight * FreightPrice;
            dbds1.SetValue("U_TotalPrice", dbds1.Offset, Freightsum.ToString());
            if (dbds1.GetValue("U_FreightPayMethod", dbds1.Offset).Trim() == "PP")
                dbds1.SetValue("U_PWeightCharge", dbds1.Offset, Freightsum.ToString());
            else
                dbds1.SetValue("U_CWeightCharge", dbds1.Offset, Freightsum.ToString());
            SBLSum(FormUID);
            oForm.Freeze(false);
        }
        /// <summary>
        /// 支付方式发生变化时控制的是否可用也随之变化
        /// </summary>
        /// <param name="oForm"></param>
        /// <param name="PayMethod"></param>
        protected void SBLOtherPayChange(SAPbouiCOM.Form oForm, string PayMethod)
        {
            if (CurrentForm.Mode != BoFormMode.fm_ADD_MODE && CurrentForm.Items.Item("7").Enabled == false)
                return;
            string[] PP = new string[] { "274", "275", "277", "278", "279", "276" };
            string[] CC = new string[] { "1000103", "1000104", "1000109", "1000111", "1000122", "1000105" };
            if (PayMethod == "CC")
            {
                try
                {
                    if (PP.Contains(oForm.ActiveItem))
                    {
                        SAPbouiCOM.ComboBox ocmb = oForm.Items.Item("1000087").Specific;
                        ocmb.Active = true;
                    }
                }
                catch { }
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, PP, true);
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, CC, false);
            }
            else
            {
                try
                {
                    if (CC.Contains(oForm.ActiveItem))
                    {
                        SAPbouiCOM.ComboBox ocmb = oForm.Items.Item("1000087").Specific;
                        ocmb.Active = true;
                    }
                }
                catch { }
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, PP, false);
                SAPBoAddon.B1Assistant.Item.SetEnabled(oForm, CC, true);
            }
        }
        #endregion
        /// <summary>
        /// 选中表格行设置dbds offset
        /// </summary>
        /// <param name="Row"></param>
        private void SelectClickRowAndSetOffset(string MatrixUID, string TableName, int Row, string KeyCol = "col_LineId")
        {
            SAPbouiCOM.Matrix omtx = this.CurrentForm.Items.Item(MatrixUID).Specific;
            SAPbouiCOM.DBDataSource dbds = this.CurrentForm.DataSources.DBDataSources.Item(TableName);
            if (omtx.VisualRowCount >= Row)
            {
                omtx.SelectRow(Row, true, false);
                int cOffset = this.GetDBDSOffSet(omtx, dbds, Row, KeyCol);
                if (dbds.Offset != cOffset)
                {
                    dbds.Offset = cOffset;
                }
            }
        }
        /// <summary>
        /// 获取DBDS的Offset
        /// </summary>
        /// <param name="omtx"></param>
        /// <param name="dbds"></param>
        /// <param name="MtxcurrentRow"></param>
        /// <param name="col_Key"></param>
        /// <returns></returns>
        private int GetDBDSOffSet(SAPbouiCOM.Matrix omtx, SAPbouiCOM.DBDataSource dbds, int MtxcurrentRow, string col_Key)
        {
            string keyVal = SAPBoAddon.B1Assistant.Matrix.GetCellValue(omtx, col_Key, MtxcurrentRow).ToString().Trim();
            string FieldName = omtx.Columns.Item(col_Key).DataBind.Alias;
            string dbdsLineVal = string.Empty;
            for (int i = 0; i < dbds.Size; i++)
            {
                dbdsLineVal = dbds.GetValue(FieldName, i).Trim();
                if (keyVal.Equals(dbdsLineVal))
                {
                    return i;
                }
            }
            return -1;
        }
        /// <summary>
        /// 初始化下拉列表
        /// </summary>
        /// <author>WangPeng</author>
        protected virtual void Combobox_Initialize()
        {
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            Utils.ComboBox_Cargo_Initial(oRst, this.CurrentForm, Cargo_ComboBoxUID_Field);
            Utils.ComboBox_Main_Initial(oRst, this.CurrentForm, BnsOperation_ComboBoxUID_Field);
            if (this.BusinessType != "OR")
            {
                Utils.ComboBox_InitialItem(oRst, this.CurrentForm.Items.Item("1000093"), "DocCurrCod", "CurrName", "OCRN");//费用币种
                Utils.ComboBox_InitialItem(oRst, this.CurrentForm.Items.Item("185"), "DocCurrCod", "CurrName", "OCRN");//主单费用币种
                if (this.CurrentForm.TypeEx == B1FormTypes.ado_AVA_FF_BusinessOperation)/*空运*/
                {
                    Utils.ComboBox_InitialItem(oRst, this.CurrentForm.Items.Item("txt_asc"), "Code", "Name", "@AVA_FF_OASC");//服务编码
                }
            }
            Utils.InitialItemComboBox(this.SBOCompany, this.CurrentForm.Items.Item("336"), "Code", "Name", "@AVA_FF_DTYP", "CAST(Code AS INT)");//文件类型   暂时注释 By WangPeng 2012年8月13日 16:49:26
        }
        /// <summary>
        /// ComboBox选默认值
        /// </summary>
        /// <author>WangPeng</author>
        private void ComboBox_SelectDefault()
        {
            string DefaultVal = string.Empty;
            this.CurrentForm.Freeze(true);
            try
            {
                Utils.ComboBox_Main_SelectDefault(this.CurrentForm, AVA_OBNO, BnsOperation_ComboBoxUID_Field);
                Utils.ComboBox_Cargo_SelectDefault(this.CurrentForm, Cargo_ComboBoxUID_Field, AVA_BNO1);

                this.CurrentForm.Refresh();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                this.CurrentForm.Freeze(false);
            }
        }
        /// <summary>
        /// 根据主单生成主单领用
        /// </summary>
        /// <author>WangPeng</author>
        public void AddAirOrderUsed()
        {
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            /*主单领用窗体类型*/
            string FormType_AirOrderUsed = AVA_AirOrderUsed;
            /*主单号*/
            string MBLNumber = SAPBoAddon.B1Assistant.Item.GetValue(this.CurrentForm, "1000013").ToString().Trim();
            if (string.IsNullOrEmpty(MBLNumber))
            {
                return;
            }
            /*验证主单号是否存在*/
            oRst.DoQuery(string.Format("SELECT 1 FROM [{1}] WHERE U_OrderNumber=N'{0}' ", MBLNumber, AVA_OAOD));
            if (oRst.RecordCount > 0)
            {
                string DocEntry = string.Empty;
                string SeriaNumber = string.Empty;
                oRst.DoQuery(String.Format(" SELECT AutoKey  FROM [ONNM] WHERE ObjectCode=N'{0}' ", AVA_AirOrderUsed));/*取DocEntry号*/
                if (oRst.RecordCount > 0)
                {
                    DocEntry = Convert.ToString(oRst.Fields.Item("AutoKey").Value);
                    SeriaNumber = SerialNumber.GetInstance().CreateSerialNumber(FormType_AirOrderUsed);//主单领用
                    string SQL_AddAirOrderUsed = string.Format(@"INSERT INTO [{3}](DocEntry,DocNum,[Object],[Status],CreateDate,--CreateTime,
                                                                    U_Status,U_SerialNum,U_OrderNumber,U_PortCode,U_DestinationPortC,U_DestinationPort,U_Airline,U_DocDueDate,U_UsedDate) 
                                                                    SELECT {0},{0},N'{4}',N'O',GETDATE(),N'P',N'{1}',N'{2}',U_PortCode,U_DestinationPortC,U_DestinationPort,U_Airline,GETDATE(),GETDATE()
                                                                    FROM [{5}] WHERE U_OrderNumber=N'{2}';  
                                                                UPDATE [{5}] SET U_UseCount = ISNULL(U_UseCount,0)+1 Where U_OrderNumber = '{2}'
                                                                UPDATE [ONNM] SET AutoKey=AutoKey+1 WHERE ObjectCode=N'{4}' ", DocEntry, SeriaNumber, MBLNumber, AVA_OAOU, AVA_AirOrderUsed, AVA_OAOD);
                    try
                    {
                        oRst.DoQuery(SQL_AddAirOrderUsed);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
        /// <summary>
        ///  得到团队管理者信息 得到 领导者名称
        /// </summary>
        private void GetTeamLeaderNameInformation(int empID)
        {
            SAPbobsCOM.Recordset oRs;
            oRs = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string getTeamLeaderInformation = "SELECT dept FROM OHEM WHERE empID={0}";
            string TeamLeaderName = string.Format(getTeamLeaderInformation, empID);
            oRs.DoQuery(TeamLeaderName);
            if (oRs.RecordCount > 0)
            {
                if (!string.IsNullOrEmpty(oRs.Fields.Item("dept").Value.ToString().Trim()))
                {
                    string deptCode = oRs.Fields.Item("dept").Value.ToString().Trim();
                    string deptNameStr = "SELECT Name FROM OUDP WHERE Code={0}";
                    deptNameStr = string.Format(deptNameStr, deptCode);
                    oRs.DoQuery(deptNameStr);
                    if (oRs.RecordCount > 0)
                    {
                        string deptName = oRs.Fields.Item("Name").Value.ToString().Trim();
                        SAPbouiCOM.DBDataSource dbdsf = default(SAPbouiCOM.DBDataSource);
                        dbdsf = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                        dbdsf.SetValue("U_Groups", dbdsf.Offset, deptName.ToString());
                    }
                    else
                    {
                        SAPbouiCOM.DBDataSource dbdsf = default(SAPbouiCOM.DBDataSource);
                        dbdsf = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                        dbdsf.SetValue("U_Groups", dbdsf.Offset, "");
                    }
                }
                else
                {
                    SAPbouiCOM.DBDataSource dbdsf = default(SAPbouiCOM.DBDataSource);
                    dbdsf = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                    dbdsf.SetValue("U_Groups", dbdsf.Offset, "");
                }
            }
            else
            {
                SAPbouiCOM.DBDataSource dbdsf = default(SAPbouiCOM.DBDataSource);
                dbdsf = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                dbdsf.SetValue("U_Groups", dbdsf.Offset, "");
            }
        }
        /// <summary>
        ///  得到客服的角色名称 HEM4
        /// </summary>
        public void GetClientNameInformation(int empID)
        {
            SAPbobsCOM.Recordset oRs;
            oRs = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string empInformation = "SELECT Position,dept FROM OHEM WHERE empID={0}";
            empInformation = string.Format(empInformation, empID);
            oRs.DoQuery(empInformation);
            if (oRs.RecordCount > 0)
            {
                if (!string.IsNullOrEmpty(oRs.Fields.Item("dept").Value.ToString().Trim()))
                {
                    string dept = oRs.Fields.Item("dept").Value.ToString().Trim();
                    string getTeamClientInformation = @"SELECT posID FROM OHPS WHERE name=N'客服' ";
                    //查询客服posID使用
                    SAPbobsCOM.Recordset oRsClient;
                    oRsClient = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                    oRsClient.DoQuery(getTeamClientInformation);
                    if (oRsClient.RecordCount > 0)
                    {
                        string ClientPosID = oRsClient.Fields.Item("posID").Value.ToString().Trim();
                        //得到客服名称
                        SAPbobsCOM.Recordset oRsClientName;
                        oRsClientName = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                        string ClientNameStr = "SELECT jobTitle  FROM OHEM WHERE Position={0} AND dept={1} ";
                        ClientNameStr = string.Format(ClientNameStr, ClientPosID, dept);
                        oRsClientName.DoQuery(ClientNameStr);
                        if (oRsClientName.RecordCount > 0)
                        {
                            string laderName = oRsClientName.Fields.Item("jobTitle").Value.ToString().Trim();
                            SAPbouiCOM.DBDataSource dbdsf2 = default(SAPbouiCOM.DBDataSource);
                            dbdsf2 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                            dbdsf2.SetValue("U_ServiceName", dbdsf2.Offset, laderName.ToString());
                        }
                        else
                        {
                            SAPbouiCOM.DBDataSource dbdsf2 = default(SAPbouiCOM.DBDataSource);
                            dbdsf2 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                            dbdsf2.SetValue("U_ServiceName", dbdsf2.Offset, "");
                        }
                    }
                    else
                    {
                        SAPbouiCOM.DBDataSource dbdsf2 = default(SAPbouiCOM.DBDataSource);
                        dbdsf2 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                        dbdsf2.SetValue("U_ServiceName", dbdsf2.Offset, "");
                    }
                }
                else
                {
                    SAPbouiCOM.DBDataSource dbdsf2 = default(SAPbouiCOM.DBDataSource);
                    dbdsf2 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                    dbdsf2.SetValue("U_ServiceName", dbdsf2.Offset, "");
                }
            }
            else
            {
                SAPbouiCOM.DBDataSource dbdsf2 = default(SAPbouiCOM.DBDataSource);
                dbdsf2 = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
                dbdsf2.SetValue("U_ServiceName", dbdsf2.Offset, "");
            }
        }

        /// <summary>
        /// 获取客服
        /// </summary>
        public void GetServiceName()
        {
            SAPbouiCOM.DBDataSource dbds_OBNO = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
            SAPbobsCOM.Recordset oRs = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);

            string ServiceName = string.Format("SELECT U_ServiceName FROM [@AVA_USEV] T1 WHERE T1.U_UserCode=N'{0}'  AND  ISNULL(U_ServiceName,N'')<>N'' ", SBOCompany.UserSignature);

            oRs.DoQuery(ServiceName);
            if (oRs.RecordCount > 0)
            {
                dbds_OBNO.SetValue("U_ServiceName", dbds_OBNO.Offset, oRs.Fields.Item("U_ServiceName").Value.ToString().Trim());
            }
            else
            {
                dbds_OBNO.SetValue("U_ServiceName", dbds_OBNO.Offset, "");
            }

        }

        /// <summary>
        /// 刷新业务单流水号
        /// </summary>
        /// <author>WangPeng</author>
        private void RefreshSerNum()
        {
            SAPbouiCOM.DBDataSource dbds_OBNO = this.CurrentForm.DataSources.DBDataSources.Item(AVA_OBNO);
            string DocEntry = dbds_OBNO.GetValue("DocEntry", dbds_OBNO.Offset).Trim();
            if (string.IsNullOrEmpty(DocEntry))
            {
                return;
            }
            SAPbobsCOM.Recordset oRst = SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
            string SQL_GetSerialNum = string.Format("SELECT U_SerialNum FROM [{0}] WHERE DocEntry={1} ", AVA_OBNO, DocEntry);
            oRst.DoQuery(SQL_GetSerialNum);
            if (oRst.RecordCount > 0)
            {
                dbds_OBNO.SetValue("U_SerialNum", dbds_OBNO.Offset, oRst.Fields.Item("U_SerialNum").Value);
            }
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(oRst);
        }

        /// <summary>
        /// 主单领用复制到业务单
        /// </summary>
        /// <author>WangPeng</author>
        private void CopyFromAirOrderUsed(string ParentFormUID)
        {
            Form oForm = default(SAPbouiCOM.Form);
            Form oParentForm = default(SAPbouiCOM.Form);
            DBDataSource dbds_Parent = default(SAPbouiCOM.DBDataSource);
            DBDataSource dbds = default(SAPbouiCOM.DBDataSource);
            string BaseEntry = string.Empty;
            Dictionary<string, string> Dic_FromFieldToField = new Dictionary<string, string>();/*key：FromField; val:ToField*/
            #region 主单领用复制到 业务单赋值字典
            Dic_FromFieldToField.Add("DocEntry", "U_MBLEntry");
            Dic_FromFieldToField.Add("U_OrderNumber", "U_MBLNumber");
            Dic_FromFieldToField.Add("U_PortCode", "U_EndPortCode");
            Dic_FromFieldToField.Add("U_DestinationPortC", "U_EndPortThCode");
            Dic_FromFieldToField.Add("U_DestinationPort", "U_EndPort");
            //Dic_FromFieldToField.Add("U_AirlineCode", "U_FreighterCode");
            //Dic_FromFieldToField.Add("U_Airline", "U_FreighterName");
            Dic_FromFieldToField.Add("U_CompanyC", "U_CardCode");
            Dic_FromFieldToField.Add("U_Company", "U_CardName");
            Dic_FromFieldToField.Add("U_Contact", "U_CntctCode");
            #endregion
            try
            {
                oForm = CurrentForm;
                Utils.SetRemarkByItem(this.CurrentForm, "13", "ABC");
                SBOApp.Menus.Item(B1MenuTypes.sys_Add).Activate();

                dbds = oForm.DataSources.DBDataSources.Item(AVA_OBNO);
                oParentForm = SBOApp.Forms.Item(ParentFormUID);

                IEnumerator dbdsEnumerator = oParentForm.DataSources.DBDataSources.GetEnumerator();
                dbds_Parent = oParentForm.DataSources.DBDataSources.Item("@AVA_FF_OAOU");

                BaseEntry = dbds_Parent.GetValue("DocEntry", dbds_Parent.Offset).Trim();

                oForm.DataSources.UserDataSources.Item("BaseEntry").Value = BaseEntry;//指向父窗体
                oForm.DataSources.UserDataSources.Item("ParentUID").Value = ParentFormUID;//指向父窗体

                Recordset oRst = this.SBOCompany.GetBusinessObject(BoObjectTypes.BoRecordset);
                string SQL_GetNextDocentry = String.Format("SELECT AutoKey FROM ONNM  WHERE OBJECTCODE = N'{0}'", oForm.BusinessObject.Key);
                oRst.DoQuery(SQL_GetNextDocentry);

                dbds.SetValue("DocEntry", dbds.Offset, oRst.Fields.Item("AutoKey").Value.ToString());
                SerialNumber.GetInstance().GetSerialNumberByProc(oForm);
                Utils.InitialCargoComboBox(this.SBOCompany, oForm, Cargo_UID_Field);

                dbds.SetValue("U_DocDate", dbds.Offset, DateTime.Now.ToString("yyyyMMdd"));
                dbds.SetValue("U_BaseType", dbds.Offset, oParentForm.TypeEx.Trim());
                dbds.SetValue("U_BaseEntry", dbds.Offset, BaseEntry);
                #region  从主单领用复制值
                foreach (string FieldFrom in Dic_FromFieldToField.Keys)
                {
                    dbds.SetValue(Dic_FromFieldToField[FieldFrom], dbds.Offset, dbds_Parent.GetValue(FieldFrom, dbds_Parent.Offset).Trim());
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 设置Tab是否隐藏
        /// </summary>
        /// <author>WangPeng</author>
        internal void SetTabHidden(string ItemUID, string TabUID)
        {
            this.CurrentForm.Freeze(true);
            SAPbouiCOM.CheckBox ocheck_IsDBL = this.CurrentForm.Items.Item(ItemUID).Specific;
            this.CurrentForm.Items.Item(TabUID).Visible = !ocheck_IsDBL.Checked;
            this.CurrentForm.Refresh();
            this.CurrentForm.Freeze(false);
        }
        #endregion
    }
}
